readdir - PHP Can't Find First File In DIR When It's Named 'original.jpg' -


i have simple function returns valid image path display. passed url that's stored particular row in db. basic functionality is:

  • if url has trailing slash it's directory; return first file in directory. if there aren't any, return "default image"
  • if url image, see exists, otherwise use first rule.

it works perfectly, except if folder contains file named 'original.jpg', displays default image. if add file, can use 'original.jpg'. if rename 'original.jpeg' or 'ori.jpg' (or shorter) works. filename i've encountered behaves way.

function displayfile($file){     $imgpath = "./img/path/";      // if folder specified or file doesn't exists; use first available file     if( substr($file, -1) == '/' || !file_exists($imgpath . $file) ){         // extract base path         $file = strstr( $file, '/', true );         $handle = opendir($imgpath . $file);         $entry = readdir($handle);         $firstfile = '';         while (false !== ($entry = readdir($handle))) {             if( substr($entry, 0, 1) != '.' ){                 $firstfile = $entry;                 break; // break isn't problem             }         }         // no file found; use default         if( $firstfile == '' ){ return $imgpath . "paw.png"; }         // found file use         else{ return $imgpath . $file . '/' . $firstfile; }     } else {         // file name valid; use         return $imgpath . $file;     }     closedir($imgpath); } 

you're calling readdir twice, skipping first entry.

$entry = readdir($handle); 

remove line , should go.


Comments