Search for files in a directory

I have a directory with a lot of files inside:

pic_1_79879879879879879.jpg
pic_1_89798798789798789.jpg
pic_1_45646545646545646.jpg
pic_2_12345678213145646.jpg
pic_3_78974565646465645.jpg
etc...

I need to specify only pic_1_ files. Any idea how I can do this? Thanks in advance.

+3
source share
5 answers

Opend dir function will help you

$dir ="your path here";

$filetoread ="pic_1_";
    if (is_dir($dir)) {
        if ($dh = opendir($dir)) {
            while (($file = readdir($dh)) !== false) {
               if (strpos($file,$filetoread) !== false)
                echo "filename: $file : filetype: " . filetype($dir . $file) . "\n";
            }
            closedir($dh);
        }
    }

good luck see php.net opendir

+4
source

Use the glob () function

foreach (glob("directory/pic_1_*") as $filename) {
  echo "$filename";
}

Just change directoryin the glob call to the correct path.

It does it all in one shot and grabs a list of files and then filters them.

+9
source

glob() :

glob - ,

:

foreach (glob("pic_1*.jpg") as $file)
{
    echo $file;
}
+4

scandir, , preg_grep, , , .

+1

http://nz.php.net/manual/en/function.readdir.php

<?php
if ($handle = opendir('.')) {
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            echo "$file\n";
        }
    }
    closedir($handle);
}
?>

you can change this code to check the file name to see if it starts with pic_1_ using something like this

if (substr($file, 0, 6) == 'pic_1_')

Manual link for substr

http://nz.php.net/manual/en/function.substr.php

+1
source

All Articles