dsf8897 2018-01-02 19:36
浏览 82
已采纳

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 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); 
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏