MY mENU


Tuesday 20 March 2012

Random Ad Rotator in PHP

This is a simple random image script which is ideal for displaying basic images from a text file.
The first step that you need to do is to create your file for storing your images and then insert the names of the images. In the example here I called the file images1.txt . Each one of the entries is on a seperate line and in this case because I stored the files in a sub-directory I inserted that also . the structure of the file was like this

image/banner1.gif
image/banner2.gif
image/banner3.gif

and so on. Now we get to the script that will display a random image and again this is straight forward enough.

#random images example
#this is your file
$file = "images1.txt";
#open the file
$fp = file($file);
#generate a random number
srand((double)microtime()*1000000);
#get one of the entries in the file
$random_image = $fp[array_rand($fp)];
#display the entry
echo "";
?>

Nothing ground breaking here , we open a file , we then generate a randomnumber, we then get a random entry from the file and store this in the variable $random_image and then we output this as some HTML.

Note that in this example we have saved this as a seperate file and included it on the page . If the file was called random.php then we put the following code where we want the image to appear

No comments:

Post a Comment