• Howdy! Welcome to our community of more than 130.000 members devoted to web hosting. This is a great place to get special offers from web hosts and post your own requests or ads. To start posting sign up here. Cheers! /Peo, FreeWebSpace.net
managed wordpress hosting

random images in PHP

hcarlson3

New Member
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?
 
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. =)
 
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
 
This would be a little bit better...


$Array=file('wallpapers.txt');
mt_srand((double)microtime()*1000000);
?><img src="<?=$Array[mt_rand(0,count($Array))]?>">
 
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">
 
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');
 
Back
Top