Web Hosting Talk







View Full Version : Randomise a set of files?


I, Brian
09-14-2005, 01:02 PM
Sorry to ask a simple question, but I'm looking to randomise a display of images, which are called up with basic PHP include files.

So if there are 5 images, I'm calling them up as:



<!-- site content above -->
<?PHP include("/home/user/public_html/image1.php"); ?>
<?PHP include("/home/user/public_html/image2.php"); ?>
<?PHP include("/home/user/public_html/image3.php"); ?>
<?PHP include("/home/user/public_html/image4.php"); ?>
<?PHP include("/home/user/public_html/image5.php"); ?>
<!-- footer below -->



How would I randomise with a script within the body itself?

Many thanks for any replies.

Flasher
09-15-2005, 02:51 PM
You can write something like this:

$random_number=rand (1, 5 );
include("/home/user/public_html/image$random_number.php");

where the function rand ( 1, 5); simply returns a random integer from 1 to 5…

Flasher
09-15-2005, 03:05 PM
You can write something like this:

$random_number=rand (1, 5 );
include("/home/user/public_html/image$random_number.php");

where the function rand ( 1, 5); simply returns a random integer from 1 to 5…

Dan L
09-15-2005, 04:26 PM
Flasher's idea works, but could be improved.

If all of the files are in the same directory, the following would automagically figure out how many files there are.. <?php
# EDIT
$dir = 'image_directory/';
# /EDIT

$handle = opendir($dir);
while(false !== ($current = readdir($handle))) {
if(($current != '.') && ($current != '..')) {
$files[] = $current;
}
}

$thisFile = random(0,sizeof($files));
include $thisFile;
?>