php脚本显示从文本文件中提取其URL的随机图像

时间:2018-01-02 19:36:15

标签: php image random

我将这个脚本放在一个文件(名为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" />

它运作正常。

我希望通过从带有线条的文本文件中拉出网址来显示随机图片,每行都是图片网址。 怎么做?

最终更新:这对我有用。

<?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编写的脚本,但注释掉了最后一个标题标记。

1 个答案:

答案 0 :(得分:1)

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

$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); 
?>