【问题标题】:php script to display a random image pulling their urls from a text filephp 脚本显示随机图像,从文本文件中提取其 url
【发布时间】:2018-01-02 19:36:14
【问题描述】:

我在一个文件(称为 random.php)中有这个脚本,它显示了它所在文件夹中的随机图像:

<?php 
$pics = glob('*.jpg', GLOB_NOSORT); 
$pic = $pics[array_rand($pics)]; 
header("Content-type: image/jpeg"); 
header("Content-Disposition: filename=\"" . basename($pic) . "\""); 
readfile($pic); 
?>

我这样称呼它:

<img class="random" src="http://www.example.com/random.php" />

它工作正常。

我想通过从一个充满行的文本文件中提取它们的 URL 来显示随机图片,每一行都是一个图像 URL。 如何做到这一点?

最终更新:这对我有用。

<?php 
$file = 'random.txt';

if (!is_readable($file)) {
    exit('File list does not exist, or is not readable by the webserver.');
}

$pics = file('random.txt', FILE_SKIP_EMPTY_LINES); 

$pic = $pics[array_rand($pics)]; 

if (!getimagesize($pic)) {
    exit('Image does not exist, or is not readable by the webserver.');
}

/// content type
header('Content-Type: image/jpeg');
// prevent caching (so its random)
header("Cache-Control: no-cache, no-store, must-revalidate");
header("Pragma: no-cache");
header("Expires: 0");
//


readfile($pic); 
?>

Lawrence Cherone 在下面精心编译的脚本,但注释掉了最后一个标题标签。

【问题讨论】:

    标签: php image random


    【解决方案1】:

    glob('*.jpg', GLOB_NOSORT); 换成file()

    $pics = file('/path/to/file.txt', FILE_SKIP_EMPTY_LINES);

    试试这个,添加错误检查:

    <?php 
    $file = 'random.txt';
    
    if (!is_readable($file)) {
        exit('File list does not exist, or is not readable by the webserver.');
    }
    
    $pics = file('random.txt', FILE_SKIP_EMPTY_LINES); 
    
    $pic = $pics[array_rand($pics)]; 
    
    if (!getimagesize($pic)) {
        exit('Image does not exist, or is not readable by the webserver.');
    }
    
    // content type
    header('Content-Type: image/jpeg');
    // prevent caching (so its random)
    header("Cache-Control: no-cache, no-store, must-revalidate");
    header("Pragma: no-cache");
    header("Expires: 0");
    //
    header('Content-Disposition: filename="'.basename($pic).'"');
    
    readfile($pic); 
    ?>
    

    【讨论】:

    • 不要将代码放入 cmets,而是用您的确切代码更新您的问题。您需要对其进行调试,因为您的输出空格或 file() 正在引发错误(可能是权限或未找到),并且在设置标头时会引发错误。
    • 正如你所建议的,我用需要调试的代码更新了我的原始帖子。您能否按照应有的方式编写完整的脚本?我只知道复制粘贴脚本,谢谢理解。
    • @Lawrence random.txt的内容只有两行,每行都是google托管的图片的URL
    • @Konstantinos 查看更新的代码,我已经对其进行了测试,它工作正常。
    • @Konstantinos 添加了一些额外的标头来停止浏览器缓存。
    猜你喜欢
    • 1970-01-01
    • 2012-05-02
    • 1970-01-01
    • 1970-01-01
    • 2013-11-19
    • 2017-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多