Jump to content

Randomly display any image from a set folder?


djmike

Recommended Posts

I am looking for a PHP script that will randomly display an image from a folder of around 20 images, although there will be more soon. The images names are all initials, e.g. TY. I could do a script to pick images if their names were all number going up from 1, but I'm not sure if this is possible with the above?
Thanks for any suggestions
[code]<?php
// in the folder with the images
foreach (glob("*.jpg") as $filename) {
    $image[$i] = $filename;
$i++;
}
$rand_image = rand(0,count($image)-1);
$tmp = $image[$rand_image];
$size = getimagesize($tmp);
echo "<img src='". $tmp. "' ". $size[3]. " alt='". $tmp. "'>";
?> [/code]
Thanks, that works fantastically.

I just need to now change it so that upon clicking the picture (using <a href) the user is directed to a php page with ?t= followed by the initial that were the picture's name. So for the image TY.jpg, the link would be mysite.com/viewer.php?t=TY

However, as I created an array, I only have the complete paths stored not the original files. Is the best way to create another array for the file names, ut I'm not sure how this would work it may randomise twice so the link doesn't match the image

Thanks again
[code]
<?php
// in the folder with the images
foreach (glob("*.jpg") as $filename) {
    $image[$i] = $filename;
$i++;
}
$rand_image = rand(0,count($image)-1);
$tmp = $image[$rand_image];
$size = getimagesize($tmp);

$url_path = "../relative/path/to/folder/where"; // where viewer.php exists - adjust to suit.

// what's before the . in the image name?
$bits = explode(".",$tmp); // $bits[0] will be TY, etc.
$url = $url_path. "/viewer.php?t=". $bits[0];

echo "<a href='". $url. "'><img src='". $tmp. "' ". $size[3]. " alt='". $tmp. "' border='0'/></a>";
?>[/code]

That should help you out as long as you have the right relative path from the images folder to viewer.php.  You can always view-source on the generated image page to see what URL it's pointing to
Thanks so much for the help, I got it sorted, but bits[0] display the whole file path and so didn't work. I had to explode it further to remove the file path:
[code]
$bits = explode(".",$tmp) ; // $bits[0] will be filepath/TY, etc.
$bits2 = explode("path/",$bits[0]) ; // $bits2[1] will be TY, etc.
[/code]

Thanks again

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.