1
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);
  }
...

我在 Wordpress 中使用它,页面加载速度很慢,但也可能是因为上面有很多图像。我只是想确保我没有做一些因性能原因而令人不悦的事情。

4

3 回答 3

3

那么你可以让它更有效率:

$extension = strtoupper(pathinfo($file, PATHINFO_EXTENSION));  
if (in_array($extension(array('PNG', 'JPG', 'JPEG', 'GIF'))) {
    echo '<img src="$path/$file" />'; 
}  

甚至使用glob()而不是 opendir/readdir/closedir... 因为你可以给它一个文件扩展名的模式。

但它本身并没有什么缓慢的地方

于 2010-12-14T08:43:35.537 回答
3

我们不能确切地说 opendir 很慢,因为它们有许多会影响性能的配置值。

您应该做的是对应用程序中的代码段进行基准测试,如下所示:

$start = microtime(true);
//Your Code
$end = (microtime(true) - $start);

并准确查看处理所需的时间。

其他一些提示:

$ext == "png" OR $ext == "PNG"是多余的,你应该使用$ext = strtolower(end($parts));然后只使用:

$ext == "png" OR $ext == "jpg" OR $ext == "jpeg" OR $ext == "gif"

更好的是你可以使用

if(in_array($ext,array("png","jpg","jpeg","gif"))){}

也不要OR只使用双管道运算符作为 or 条件:||

于 2010-12-14T08:46:31.067 回答
2

获取 firefox“quickjava”插件。

通过这种方式,您可以禁用图像(通过单击右上角的蓝色 I 使其变为红色)并在没有任何图像的情况下测试网页的性能。

于 2010-12-14T08:40:29.623 回答