I’ve written a PHP script that iterates through a given folder, extracts all the images from there and displays them on an HTML page (as tags). The size of the page is about 14 KB, but it takes the page almost 15 seconds.
Here’s the code:
function displayGallery( $gallery, $rel, $first_image ) {
$prefix = "http://www.example.com/";
$path_to_gallery = "gallery_albums/" . $gallery . "/";
$handler = opendir( $path_to_gallery ); //opens directory
while ( ( $file = readdir( $handler ) ) !== false ) {
if ( strcmp( $file, "." ) != 0 && strcmp( $file, ".." ) !=0 ) {
//check for "." and ".." files
if ( isImage( $prefix . $path_to_gallery . $file ) ) {
echo '<a href="' . $path_to_gallery . $file . '"></a>';
}
}
}
closedir( $handler ); //closes directory
}
function isImage($image_file) {
if (getimagesize($image_file)!==false) {
return true;
} else {
return false;
}
}
I looked at other posts, but most of them deal with SQL queries, and that’s not my case.
Any suggestions how to optimize this?
My assumption is that
isImageis the problem. I’ve never seen it before. Why not just check for particular file extensions? That’s pretty quick.Update: You might also try switching to use
exif_imagetype()which is likely faster thangetimagesize()Putting that check into the top function is also going to be faster. Neither of those functions was meant to be done over a web connection – avoid that altogether. Best to stick with the file extension.Do you not already have access to the files directly? Every time you look something up over the web, it’s going to take a while – you need to wait for the entire file to download. Look up the files directly on your system.
Use
scandirto get all the filenames at once into an array and walk through them. That will likely speed things up as I assume there won’t be a back and forth to get things individually.Instead of doing
strcmpfor.and..just do$file != '.' && $file != '..'Also, the speed is going to depend on the number of files being returned, if there are a lot it’s going to be slow. The OS can slow down with too many files in a directory as well. You’re looping over all files and directories, not just images so that’s the number that counts, not just the images.