I have a simple function that returns a valid image path to display. It is passed the URL that's stored for a particular row in my DB. The basic functionality is:
- If the URL has a trailing slash it's a directory; return the first file in that directory. If there aren't any, return the "default image"
- If the URL is an image, see that it exists, otherwise use the first rule.
It works perfectly, except if the folder only contains a file named 'original.jpg', it displays the default image. If I add another file, it can use 'original.jpg'. If I rename it to 'original.jpeg' or 'ori.jpg' (or shorter) it works. This is the only filename I've encountered that behaves this way.
function displayFile($file){
$imgPath = "./img/path/";
// If folder was 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; // This break isn't the problem
}
}
// No file found; use default
if( $firstFile == '' ){ return $imgPath . "paw.png"; }
// Found a file to use
else{ return $imgPath . $file . '/' . $firstFile; }
} else {
// File name is valid; use it
return $imgPath . $file;
}
closedir($imgPath);
}