Rilcon42 Rilcon42 - 1 year ago 188
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
    _thumb
    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

    <?php
    $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
    $thumb=explode('.',$imgDir.$file[$i]);
    $thumb=$thumb[0].'_thumb.'.$thumb[1];
    //echo('<br>'.$thumb);
    //echo('<br>'.$file[$i]);
    ?>


Answer Source

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

<?php
$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