View Full Version : random images in PHP
hcarlson3
May 11th, 2001, 12:28
Alright, I made this random image script in PHP:
$FileName = "wallpapers.txt";
$FilePointer = fopen($FileName,"r");
$Array = file($FileName);
fclose($FilePointer);
srand((double)microtime() * 1000000);
$RandomNumber = rand(1,52);
$picture = $Array[$RandomNumber];
echo "<img src=\"$picture\">";
wallpapers.txt has the locations of all of the images, 1 image per line.
Is that how you would do it, or is there another, better way?
BillWill
May 12th, 2001, 19:23
I haven't really checked the syntax closely but that looks about right... Change the 1,52 to 0,51 because arrays always start at 0. =)
lucifer
May 13th, 2001, 13:29
you shouldn't need the lines
$FilePointer = fopen($FileName,"r");
fclose($FilePointer);
as file() will just fill the array anyway
I'd change the 52/51 to count($Array) so that you can add extra images to the txt file
being picky change \" to ' in the last line looks cleaner
Woofcat
May 13th, 2001, 17:00
This would be a little bit better...
$Array=file('wallpapers.txt');
mt_srand((double)microtime()*1000000);
?><img src="<?=$Array[mt_rand(0,count($Array))]?>">
KapTinKiRk
May 13th, 2001, 17:05
srand((double)microtime()*1000000);
$input = array(
"01.jpg",
"02.jpg",
"03.jpg",
"04.jpg"
);
$random_image = array_rand($input);
header ("Location: $input[$random_image]\n\n");
...
Gets the names from the script itself rather than a remote file. And prints the image as a header location, so you would call it on a page as a regular image tag.
<img src="random.php">
Woofcat
May 13th, 2001, 18:25
If you want the script to return the image directly without grabbing names from an external file this would be better...
header('Content-Type: image/gif');
srand((double)microtime()*1000000);
readfile(array_rand(range(0,50)).'.gif');
Powered by vBulletin® Version 4.1.7 Copyright © 2012 vBulletin Solutions, Inc. All rights reserved.