This is my code:
$file = 'images/img_' . $post->_id . '.jpg'; // images/img_1.jpg
if (file_exists($file) && is_file($file)) {
//show the image
echo '<img src="' . $file . '" class="img-responsive" />';
}
else {
// show default image
echo '<img src="images/default.gif" class="img-responsive" />';
}
What this basicly does is to check if the an image (eg img_1.jpg) exist in my images folder and display it, if not it shows a default image.
This works fine, the only problem, as you probably 've seen, is that it checks only the .jpg files and not *.gif or *.png too (the file could also be img_1.gif or img_1.png, right? ) .
How can I make sure that it will check against all valid file types too and show the file with the correct format?
The most efficient way to do this is probably to store the extension in the database, that way you're not scanning your file system for matches.
However, you could also use the glob();
; function and check if results has anything.
$result = glob('images/img_' . $post->_id . '.*');
If you want to further narrow down your extension types you can do that like this:
$result = glob('images/img_' . $post->_id . '.{jpg,jpeg,png,gif}', GLOB_BRACE)
New code might look something like this (untested but you get the idea):
$result = glob('images/img_' . $post->_id . '.{jpg,jpeg,png,gif}', GLOB_BRACE);
if(!empty($result)) {
//show the image
echo '<img src="' . $result[0]. '" class="img-responsive" />';
} else {
// show default image
echo '<img src="images/default.gif" class="img-responsive" />';
}