Is this PHP opendir() very taxing on the server?
if (is_dir($dir)) {
if($handle = opendir($dir)) {
while($file = readdir($handle)) {
// Break the filename by period; if there's more than one piece, grab the last piece.
$parts = explode(".", $file);
if (开发者_开发百科is_array($parts) && count($parts) > 1) {
$ext = end($parts);
// If it's an image that we want, echo the code.
if ($ext == "png" OR $ext == "PNG" OR $ext == "jpg" OR $ext == "JPG" OR $ext == "jpeg" OR $ext == "JPEG" OR $ext == "gif" OR $ext == "GIF")
echo "<img src=\"$path/$file\" />";
}
}
closedir($handle);
}
...
I'm using it in Wordpress, and the page loads pretty slowly, but it could also be from having a lot of images on it. I just wanted to make sure I wasn't doing something that was frowned upon for performance reasons.
Well you could make it more efficient:
$extension = strtoupper(pathinfo($file, PATHINFO_EXTENSION));
if (in_array($extension(array('PNG', 'JPG', 'JPEG', 'GIF'))) {
echo '<img src="$path/$file" />';
}
or even using glob() rather than opendir/readdir/closedir... because you can give it a pattern of file extensions.
But there's nothing inherently slow about it
We cant exactly say that opendir is slow as they is many configuration values that can effect performance.
what you should do is benchmark the segement of code in your app like so:
$start = microtime(true);
//Your Code
$end = (microtime(true) - $start);
and see exactly how long it had taken to process.
Some other tips:
$ext == "png" OR $ext == "PNG"
is redundant, you should use $ext = strtolower(end($parts));
and then just use:
$ext == "png" OR $ext == "jpg" OR $ext == "jpeg" OR $ext == "gif"
better yet you can just use
if(in_array($ext,array("png","jpg","jpeg","gif"))){}
also instead of using OR
just use the double piped operator for the or condition: ||
.
Get the firefox "quickjava" plugin.
This way you can disable images (by clicking the blue I in the right corner so it turns red) and test the performance of your webpage without any images.
精彩评论