Blinding Light: Free Web Layouts, Anime Transparent PNG, PS Brushes, Coding Tutorials and more!

Blinding Light: Web Layouts, PS Brushes, Coding Tutorials, Transparent PNG

Display Random Images From A Directory Using PHP

Have a bunch of images in a directory you want to display? Well, PHP can help you in doing it.

This PHP tutorial is a variation of the Randomizing With PHP. So I will not repeat whatever is explained there.

The PHP Code

<?php

// LOCATION OF IMAGE DIRECTORY
// DO NOT FORGET TO BEGIN AND END WITH A /
$imageDirectory = "/images/directory/";

// OPENS IMAGES DIRECTORY
$dirHandle = opendir($_SERVER['DOCUMENT_ROOT'].$imageDirectory);

// READS FILES IN THE DIRECTORY
while (false !== ($dirFile = readdir($dirHandle)))
{
	// STRIPS . AND .. FROM FILES IN DIRECTORY
	// DON'T REMOVE IF YOU WANT THIS SCRIPT TO WORK
	if ($dirFile != "." && $dirFile != "..")
	{
		// PUTS FILES INSIDE THE DIRECTORY IN AN ARRAY
		$randomFile[] = $dirFile;
	}
}

// DISPLAYS RANDOM IMAGE FROM THE DIRECTORY
// READ Randomizing With PHP TUTORIAL
echo "<img src=\"".$imageDirectory.$randomFile[rand(0,count($randomFile)-1)]."\" alt=\"Random Image\">\n";

// CLOSES DIRECTORY
closedir($dirHandle);

?>

Comments are placed on the code to explain what each part of the PHP code does.

The only thing you really need to change is the location of the image directory. Example, if your random images are located in http://www.blinding-light.com/images/random, the value for $imageDirectory variable becomes /images/random/.

Conclusion

Quite simple, huh? Just remember that with this code, all the files and folders in the directory you put in will be displayed as images so make sure all the files in the directory are image files and that there are no folders within it.

If you have any questions or if you want to discuss this tutorial, you may post at Blinding Light MB.

Web site design, scripting and contents © 2003-08 Miko Reznor.
No part of this site may be republished without permission.