When displaying images on our website, we check if the file exists with a call to file_exists()
. We fall back to a dummy image if the file was missing.
Howe
Create a hashing routine for sharding the files into multiple sub-directories.
filename.jpg -> 012345 -> /01/23/45.jpg
Also, you could use mod_rewrite to return your placeholder image for requests to your image directory that 404.
file_exists()
is automatically cached by PHP. I don't think you'll find a faster function in PHP to check the existence of a file.
See this thread.
If you want to check existence of an image file, a much faster way is to use getimagesize !
Faster locally and remotely!
if(!@GetImageSize($image_path_or_url)) // False means no imagefile
{
// Do something
}
I'm not even sure if this will be any faster but it appears as though you would still like to benchmark soooo:
Build a cache of a large array of all image paths.
$array = array('/path/to/file.jpg' => true, '/path/to/file2.gif' => true);
Update the cache hourly or daily depending on your requirements. You would do this utilizing cron to run a PHP script which will recursively go through the files directory to generate the array of paths.
When you wish to check if a file exists, load your cached array and do a simply isset() check for a fast array index lookup:
if (isset($myCachedArray[$imgpath])) {
// handle display
}
There will still be overhead from loading the cache but it will hopefully be small enough to stay in memory. If you have multiple images you are checking for on a page you will probably notice more significant gains as you can load the cache on page load.
I came to this page looking for a solution, and it seems fopen may do the trick. If you use this code, you might want to disable error logging for the files that are not found.
<?php
for ($n=1;$n<100;$n++){
clearstatcache();
$h=@fopen("files.php","r");
if ($h){
echo "F";
fclose($h);
}else{
echo "N";
}
}
?>
Are they all in the same directory? If so it may be worth getting the list of files and storing them in a hash and comparing against that rather than all the file_exists lookups.