dsf8897
2018-01-02 19:36 阅读 44
已采纳

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

I have this script in a file (called random.php) which displays a random image from the folder where it resides:

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

I am calling it as follows:

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

It works properly.

I want instead to make it to display random pictures by pulling their urls from a text file full with lines, each line being an image url. How to do this?

Final update: This is what worked for me.

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

Is the script kindly compiled below by Lawrence Cherone but commenting out the last header tag.

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享

1条回答 默认 最新

  • 已采纳
    douqianmin5367 douqianmin5367 2018-01-02 19:39

    Switch out glob('*.jpg', GLOB_NOSORT); for file().

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

    Try this, with added error checking:

    <?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); 
    ?>
    
    点赞 评论 复制链接分享

相关推荐