澳洲大头 发表于 2009-12-18 14:59:58

Random images from a directory 2

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.



<?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."\" 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.
页: [1]
查看完整版本: Random images from a directory 2