我在一个有多个div
容器的网站上工作。它们都有一个共同的类,称为qcnt
,定义了它们的结构,一般外观和位置。
他们每个人也分配了一个不同的类,大约100个中的一个,给他们每个人一个大约100个各自的大约4个图像集的图像作为background-image
。这些集合目前被组织在每个类的文件夹中。每个类的CSS当前引用一个名为random.php
的文件,我在web上发现它会自动返回它们各自文件夹中的随机图像之一。
我认为这是一个非常性能密集型的任务,让服务器每次页面访问运行25到100个或更多的容器。
我想知道在这种情况下哪种方法更合理有效。提前感谢!
我可以在这里发布random.php
代码,但我猜我的一般结构从一开始就是一种无效的方法。
编辑:好吧,我没有意识到这一点,这里是代码:
<?php
$folder = '.';
$extList = array();
$extList['gif'] = 'image/gif';
$extList['jpg'] = 'image/jpeg';
$extList['jpeg'] = 'image/jpeg';
$extList['png'] = 'image/png';
$img = null;
if (substr($folder,-1) != '/') {
$folder = $folder.'/';
}
if (isset($_GET['img'])) {
$imageInfo = pathinfo($_GET['img']);
if (
isset( $extList[ strtolower( $imageInfo['extension'] ) ] ) &&
file_exists( $folder.$imageInfo['basename'] )
) {
$img = $folder.$imageInfo['basename'];
}
} else {
$fileList = array();
$handle = opendir($folder);
while ( false !== ( $file = readdir($handle) ) ) {
$file_info = pathinfo($file);
if (
isset( $extList[ strtolower( $file_info['extension'] ) ] )
) {
$fileList[] = $file;
}
}
closedir($handle);
if (count($fileList) > 0) {
$imageNumber = time() % count($fileList);
$img = $folder.$fileList[$imageNumber];
}
}
if ($img!=null) {
$imageInfo = pathinfo($img);
$contentType = 'Content-type: '.$extList[ $imageInfo['extension'] ];
header ($contentType);
readfile($img);
} else {
if ( function_exists('imagecreate') ) {
header ("Content-type: image/png");
$im = @imagecreate (100, 100)
or die ("Cannot initialize new GD image stream");
$background_color = imagecolorallocate ($im, 255, 255, 255);
$text_color = imagecolorallocate ($im, 0,0,0);
imagestring ($im, 2, 5, 5, "IMAGE ERROR", $text_color);
imagepng ($im);
imagedestroy($im);
}
}
?>
首先,在你的random.php中添加一个http缓存过期:如何使用HTTP缓存头与PHP
你不需要太多,从1分钟到半小时的任何时间都应该是一个很好的平衡,这取决于你的确切需求(更低的缓存=更低的性能,但如果你做了更改,更新更快)。
其次,在CSS中添加1-100的随机变量,如下所示:random.php?b=13
random.php?b=79
random.php?b=27
random.php?b=1
...
随机变量将确保即使缓存random.php,每个容器仍将获得随机图像。但是由于您已经添加了缓存,并且将变量限制为1-100,因此无论您的站点负载如何,您将看到的平均最大调用次数是100次/缓存时间。