News Tutorials Projects Reviews Authors Contact Search Links Admin
 

Random Images : The Code

If you've just read the random quotes, this is basically the same thing. I just adapted the tutorial to suit. This script will output the HTML needed to display a random image on a page on every page load.

To begin with, you need a folder full of pictures, preferably sequentially numbered. For example, I have a folder called 'randomimages' with the files 'image_1.gif' through to 'image_15.gif'.

First, define the image directory. Try and make these things variables as much a you can, it'll save editing/updating in the long run.
<?php
$image_directory = "randomimages/";
?>

Next, pick a random number, between 1 and 15.

<?php
$random_number = rand(1,15);
?>

Next, echo the HTML linking to the pictures.

<?php
echo '<img src="'.$image_directory.'image_'.$random_number.'" alt="Random image">
?>

See how we make the img tag up out of the variables we set. This now forms a link to the graphic in the directory, provided it exists.

My full code looks like:
<?php
$image_directory = "randomimages/";

$random_number = rand(1,15);

echo '<img src="'.$image_directory.'image_'.$random_number.'" alt="Random image">
?>

Give it a go. Put the code in a HTML file somewhere, grab some images, label them up sequentially, save the file as random_image.php, and upload to any PHP enabled server.

 


Author: Markavian
Last edited on: 13th Mar, 1:35 pm
Please rate this article.

tutorial Pages