Reputation: 11
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.
Upvotes: 0
Views: 93
Reputation: 46620
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);
?>
Upvotes: 1