PDA

View Full Version : Random Images


JR
January 24 '04, 06:23 PM
Random Images

Required Knowledge: HTML, setting up PHP pages.
Keywords: Random Image, Rotation, Banner, Picture

This tutorial will show you how to display a random image, as seen in my signature (at the time of posting this)

JR
January 24 '04, 06:23 PM
Part 1: The Simple Way

This method assumes you have the images named 1.gif, 2.gif, 3.gif etc.

All you have to do is create a PHP page with this script in:

<?php
//$dir is the directory where the images are stored,
//if the images are in the same directory as the script leave it blank.
//Enter it in the following format: directoryname/
$dir = "";
//$ext is the file extension of all the files, such as .gif or .jpg.
$ext = ".gif";
//$i is the image filename. They must be named in order (e.g. 1.gif, 2.gif).
//Replace '10' with the total number of images.
$totalimages = 10;
//Do not edit below here
$i = rand(1, $totalimages);
$img = $dir.$i.$ext;
header("Location: $img");
?>

You can remove the orange comments.

If the PHP file that the script is kept in is called ‘randomimage.php’ then you can use this in your image tags on your website:
<img src=”randomimage.php” />

JR
January 24 '04, 06:23 PM
Part 2: The Other Way

If you cannot name the files 1.gif, 2.gif for any reason, then this script may be for you…

<?php
//$dirname is the directory where the images are stored.
//The images MUST be stored in a folder.
//Enter it in the following format: directoryname/
$dirname = "";
//Do not edit below here. Unless you know what you're doing of course
$dir = opendir($dirname);
$i = -1;
while (false !== ($file = readdir($dir)))
{
if (is_readable("$dirname/$file"))
{
$img_array[$i] = $file;
$i++;
}
}
$r = rand(1, $i - 1);
$img = $dirname.$img_array[$r];
header("location: $img");
?>


A draw-back of this method is that the images must be stored in a folder, as far as I know. Plus you cannot store any other file types than images in the folder, or it won’t work.

Again, if the file that this script is kept in is called ‘randomimage’ then you can use it in your img tags on your website:
<img src=”randomimage.php” />If you need to customise this script for your own needs, then just post a reply and I’ll give you some help.

ULTiMATE
January 24 '04, 07:56 PM
Well theres always a more complicated way of doing it. This will get all the images from a directory AND and sub-directory inside that one


<?php
# folder from the document_root you want to include and all sub dirs
$folder = "images";
function createimagearray($newdir){
global $folder,$newarray,$DOCUMENT_ROOT;
$dir_subdirs = array();
chdir($newdir);

$handle = opendir($newdir);

while($entry = readdir($handle)){
$dirtitle = str_replace($DOCUMENT_ROOT,"",$newdir);
$last4 = substr(strtolower($entry),-4);
if(is_dir($entry) && $entry != ".." && $entry != "."){
$dir_subdirs[] = $entry;
} elseif($entry != ".." && $entry != "." &&
($last4 == ".gif" ||
$last4 == ".jpg" ||
$last4 == ".png" ||
$last4 == ".bmp")){
$newarray .= "$dirtitle$entry||";
}
}
sort($dir_subdirs);
for($i=0; $i<count($dir_subdirs); $i++){
$array = createimagearray("$newdir$dir_subdirs[$i]/");
}
closedir($handle);
return $newarray;
}
$array = createimagearray($DOCUMENT_ROOT."/".$folder."/");
$array = substr($array, 0,-2);
$array = explode("||",$array);
function make_seed() {
list($usec, $sec) = explode(' ', microtime());
return (float) $sec + ((float) $usec * 100000);
}
srand(make_seed());
$view = $array[rand(0,(count($array))-1)];
echo "<img src=\"$view\">";
?>

[Li] Brad
January 25 '04, 02:44 AM
Nice work JR, much simpler than the traditional JavaScript method, though universal on all web servers, but mostly every web host these days offers PHP as an incentive.

[Li] Brad

justlivyalife
January 25 '04, 06:48 AM
Very nice, thanks JR :). Now to check it out :-P.

justlivyalife
January 25 '04, 08:05 AM
Got the script to work using both the 'Simple Way', and the 'Other Way' Thanks very much!

fgfgfgh
January 25 '04, 01:08 PM
this is something I recently found myself doing using ASP, in which it's equally simple.Include this code:

<%
Dim strPic

'array variable for pics
Dim x(1000)

'constant for image directory
Const mypath="/images"

'new filesystem object
Set filesystem = CreateObject("Scripting.FileSystemObject")
Set folder = filesystem.GetFolder(server.mappath(mypath))

Set filecollection = folder.Files

' Step through the files list
' keeping track of the number of files
idx=0
For Each file in filecollection
idx=idx+1
x(idx)=file.name
Next

'Choose a random picture
randomize timer
whichNo=int(rnd()*idx)+1

'Clean up objects
set filesystem=nothing
set folder=nothing
set filecollection=nothing

'Displaying the image
strPic= "<img height=82 width=181 src=" & imagepath & "/" & x(whichNO)& " alt=" & x(whichNo) & " border=0>"

%>

Then write out the pic variable in the relevant page position:

<% =strPic %>

Wired
July 6 '04, 02:24 AM
Since no one can see the above code by the banned poster, I'm re-posting it in its entirety. The original poster stated that they did not personally code it, but simply found it somewhere. I have not personally researched this code to see if it is under the GPL or copyrighted or anything, but if asked the staff of WDF will respectfully remove it from this site immediately:

<%
Dim strPic

'array variable for pics
Dim x(1000)

'constant for image directory
Const mypath="/images"

'new filesystem object
Set filesystem = CreateObject("Scripting.FileSystemObject")
Set folder = filesystem.GetFolder(server.mappath(mypath))

Set filecollection = folder.Files

' Step through the files list
' keeping track of the number of files
idx=0
For Each file in filecollection
idx=idx+1
x(idx)=file.name
Next

'Choose a random picture
randomize timer
whichNo=int(rnd()*idx)+1

'Clean up objects
set filesystem=nothing
set folder=nothing
set filecollection=nothing

'Displaying the image
strPic= "<img height=82 width=181 src=" & imagepath & "/" & x(whichNO)& " alt=" & x(whichNo) & " border=0>"

%>

Then write out the pic variable in the relevant page position:

<% =strPic %>

sectachrome
July 22 '04, 08:14 PM
ok i named all my images 1.jpg, 2.jpg, etc. and edited the script accordingly.

i uploaded my images on to my server in their own directory. do i need to upload the php file into the same directory?

im using dreamweaver. do i actually put one of the images in the spot i want? what exactly do i need to do with the image tag part?

thanks a lot! trying to get this to work is driving me nuts!

JR
July 23 '04, 05:31 AM
You don't need to put the PHP script in the same directory, just define what directory you are putting the images in in the $dir variable. You will also need to change the $ext variable to '.jpg'

The image tag you put in your HTML page, seperate from the PHP code.

Hope this helps, post a reply if it doesn't.

sectachrome
July 23 '04, 01:54 PM
okay, im having trouble with the image tag. i put it where i need it to go, put when i go to preview in browser, it says page not found. :confused:

JR
July 23 '04, 06:29 PM
Ok, first try typing in the web address of your PHP page that outputs the image. Does that work?

I think you have probably entered something incorrectly into the script, so it outputs a path that does not exist.

sectachrome
July 23 '04, 07:32 PM
http://home.comcast.net/~sk8schleg/mysiterotation/randomimage.php

splufdaddy
July 23 '04, 09:15 PM
Comcast does not offer PHP support. You'll need to find a host that supports PHP.

sectachrome
July 23 '04, 10:48 PM
dammit, i knew it was gonna be something with comcast. they suck.

what about java script?

m.mckernan
December 4 '04, 09:23 PM
Would anyone be able to show me how to manipulate this concept so that it could use flash files instead of images?

spanky192
May 21 '05, 09:10 PM
hey im new. i've been trying to search for a code like this all day long. im trying to make an html file to use as my wallpaper for windows xp to change the background from the "my pictures" directory and its subdirectories. i cant seem to get it to work. can anyone help me out

deadhippo
June 17 '05, 02:01 PM
hi, well have installed a random image script on my site and tested it and it seems to work fine
the random image is through css backround

but i have a problem..basically i want to be able to asign each picture its own link and its own tag, my server doesnt allow asp so thats out ...does anybody know how to do this