javascript - 快速轻松地从文件夹中选择一个随机文件

标签 javascript php jquery css random

我在一个有多个 div 容器的网站上工作。 它们都有一个共同的类,称为 qcnt,定义它们的结构、一般外观和位置。

他们每个人还分配了一个不同的类别,大约 100 个中的一个,给他们每个人大约 100 组图像作为 background-image。这些集合目前组织在每个类(class)的文件夹中。每个类的 CSS 当前都引用一个名为 random.php 的文件,我在网上发现该文件会自动随机返回各自文件夹中的其中一张图像。

我认为让服务器在每次访问页面时运行 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 缓存过期时间: How to use HTTP cache headers with 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/缓存时间。

关于javascript - 快速轻松地从文件夹中选择一个随机文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23765745/

相关文章:

javascript - Json休息API : Best solution for getting multiple bits of data

javascript - 使用 JavaScript 写入 HTML

php - 使用 PHPSpec 安排/执行/断言模式

php - PHP Net_SSH2-exec()如何获取命令返回码

javascript - 将鼠标悬停在列表项上时获取表格行的 ID

javascript - jquery表单提交后如何刷新特定div

javascript - 读取ICY元数据reactJS

php - Google Freebase API 一次获取名称、图像和文本

javascript - velocity.is 序列内部的函数

javascript - 改变选项(选择)元素的值?