【问题标题】:PHP Random Image Function sometimes inserts blank imagePHP随机图像函数有时会插入空白图像
【发布时间】:2014-05-17 14:17:33
【问题描述】:

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

这是 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总是在页面渲染之前完全执行。

Working example of the PHP script in action can be found here.

脚本在除主页和联系页面之外的所有页面上运行。

【问题讨论】:

    标签: php html wordpress image


    【解决方案1】:

    尝试使用 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);
    
    ?>
    

    祝你好运!

    【讨论】:

    • 这似乎工作得很好。知道为什么 opendir 方法会产生问题吗?
    • 我不确定,但这可能是 PHP 软件本身的问题。如果它解决了您的问题,请将我的答案标记为已解决。谢谢!
    • 标记为已解决。在将其标记为已解决之前,我只是在等待您的回复。我希望您就可能导致问题的原因提供意见,但不确定如果它被标记为已解决,您是否会回来。 ;)
    • 我很高兴它对你有用。非常感谢,但我不是那种人。祝你做任何你正在做的事情好运:)
    猜你喜欢
    • 1970-01-01
    • 2011-08-29
    • 2020-11-23
    • 2021-06-28
    • 1970-01-01
    • 2012-09-07
    • 2015-06-13
    • 2016-03-25
    • 1970-01-01
    相关资源
    最近更新 更多