-2

I have a php function that allows me to delete images from a certain directory. Now my problem is that in my code, i can see the index.php file listed, and i only want to show the images under it. Here is my full code:

$fid= $_POST['fid'];
    if (("submit")&&($fid != "")) {
    foreach($fid as $rfn) {
    $remove = "$dir/$rfn";
    unlink($remove);
    }
    }
    $handle=opendir($dir);
    while (($file = readdir($handle))!== false){
    if ($file != "." && $file != "..") {
    $size = filesize("$dir/$file");
    $list .= '<div class="col-md-3 text-center" style="margin-top:20px;">';
    $list .= '<img src="../inc/img/galeria/'.$file.'" class="rounded" width="100%" height="250px">';
    $list .= '<br><br>';
    $list .= '<input type="checkbox" class="form-control" name="fid[]" value="'.$file.'">';
    $list .= '</div>';
    }
    }
    closedir($handle);
    echo $list;

Now this code works just fine, the problem is it lists everything inside the directory and i want to show only the jpg, jpeg, gif or png files inside of that directory. Thanks in advance guys.

3 Answers3

1

This is how to scan a dir and only process certain files. Adapt for your use:

$handle=opendir($dir);
while ( ($file = readdir($handle)) !== false ) {
    $ext = pathinfo($file, PATHINFO_EXTENSION);
    if ( in_array($file, ['.', '..']) || ! in_array($ext, ['jpeg', 'jpg', 'gif', 'png']) ) {
        continue;
    }
    // Do something with file
}
ryantxr
  • 4,119
  • 1
  • 11
  • 25
1

You can try the following. I hope there is no syntax error. I did not run it.

foreach(glob($dir . "/*.{jpg,jpeg,png}", GLOB_BRACE) as $file) {
  // echo $file;
}
koalabruder
  • 2,794
  • 9
  • 33
  • 40
0

This fixes the issue, thank you guys for the tips!

$images = glob('/tmp/*.{jpeg,gif,png}', GLOB_BRACE);

And also:

// image extensions
$extensions = array('jpg', 'jpeg', 'png', 'gif', 'bmp');

// init result
$result = array();

// directory to scan
$directory = new DirectoryIterator('/dir/to/scan/');

// iterate
foreach ($directory as $fileinfo) {
    // must be a file
    if ($fileinfo->isFile()) {
        // file extension
        $extension = strtolower(pathinfo($fileinfo->getFilename(), PATHINFO_EXTENSION));
        // check if extension match
        if (in_array($extension, $extensions)) {
            // add to result
            $result[] = $fileinfo->getFilename();
        }
    }
}
// print result
print_r($result);

This one is even better and i have managed to make it work, shouts to @pirateofmarmara to guide me on this.