PHP随机图像函数有时会插入空白图像


PHP Random Image Function sometimes inserts blank image

我有一个函数,它打开一个预先指定的目录,使目录内的图像文件的数组,然后从数组列表中提取一个随机图像名称,以返回到网页。问题是,有时它实际上并没有提取图像名称。

下面是php代码:

<?php
    $actualpath = get_stylesheet_directory_uri() . "/img/banners/";
    // open this directory 
    $myDirectory = opendir("wp-content/themes/beautysalon/img/banners/");
    // get each entry
    while($entryName = readdir($myDirectory)) {
        $dirArray[] = $entryName;
    }
    // close directory
    closedir($myDirectory);

    function getRandomFromArray($ar) {
        mt_srand( (double)microtime() * 1000000 ); // php 4.2+ not needed
        $num = array_rand($ar);
        return $ar[$num];
    }
    $randomPicture = getRandomFromArray($dirArray);
?>

我用来在网页上显示图像的代码:

<?php
    if ( !is_front_page() ) {
        echo '<img src="' . $actualpath . $randomPicture . '"/>';
    };
?>

当代码工作时,它最终回显如下:

<src="http://sitename.com/directorypath/image.png" />

这正是我想让它做的。但是当它不起作用时,由于某种原因,它没有提取图像名称,最终输出如下所示的内容,这导致了一个破碎的图像:

<src="http://sitename.com/directorypath/" />

这就好像php在生成页面内容之前没有时间运行该函数,但我认为php总是在页面呈现之前完全执行。

PHP脚本的工作示例可以在这里找到。

脚本运行在除了首页和联系人页面以外的所有页面。

尝试使用scandir代替opendir。告诉我能不能用,不行我就修改代码。我已经在我这边测试过了,效果不错。

<?php
// Your variables...
$actualpath = get_stylesheet_directory_uri() . "/img/banners/";
$directory = 'wp-content/themes/beautysalon/img/banners/';
// Scan the directory and strip the dots that come with the array
$sd = array_diff(scandir($directory), array('..', '.'));
// Sort the array so that the numbering is correct
sort($sd);
// The random array function.
function getRandomFromArray($ar) {
    return $ar[array_rand($ar)];
}
// Your variable.
$randomPicture = getRandomFromArray($sd);
?>

祝你好运!