Rilcon42 Rilcon42 - 3 years ago 261
PHP Question

filtering for image file type and string match using glob

I am trying to look through a folder and select all image files in the folder, then generate a thumbnail name (xx.jpg would turn into xx_thumb.jpg). Right now I use scandir to iterate through the folder and subfolders, I couldn't find a glob solution that worked for me. Im on PHP version 5.2.17. Anyone have suggestions about how I can:

  1. Filter for images without the string
    specifically? My hacky if statement is driving me crazy.

  2. correctly parse the string for thumbnails? For example xx.xx.jpg does not work correctly right now. it returns xx_thumb.xx.jpg instead of xx.xx_thumb.jpg

    $file = scandir($imgDir);

    for($i=0;$i<count($file);$i++) {
    if((strpos($file[$i],'jpg') !== false||strpos($file[$i],'png') !== false) && strpos($file[$i],'_thumb') == false){
    //add the text _thumb to a thumb

Answer Source

I think you can still use scandir() instead of glob()

$img_extensions = ["jpg", "png"];

function matching_end($s1, $s2){
    return substr($s1, - strlen($s2)) === $s2;

foreach (scandir($imgDir) as $file) {
    $ext = strtolower(pathinfo($file, PATHINFO_EXTENSION));
    if ( in_array($ext, $img_extensions) && !matching_end(pathinfo($file, PATHINFO_FILENAME), "_thumb") && substr($file, 0, 1) !== "." ) {
        $thumb = pathinfo($file, PATHINFO_FILENAME) . "_thumb." . pathinfo($file, PATHINFO_EXTENSION);

This code discovers the extension correctly even if the file has an upper-case one (file like myimage.JPG is good; in order to have a stronger check you should verify its mime content, but this is not part of the question); and upper-case extensions area treated in the right way: file my-image.JPG gives a my-image_thumb.JPG result.

Files with leading dots are discarded (hidden files in GNU/Linux implementations). In addiction, "_thumb" substring is not searched in the entire filename, but should not match filename end, without the extension.

_thumb file names are correctly reconstructed by using native pathinfo() function.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download