Zend - The PHP Company




Files and Directories

Add Code


File Grabber with Random Photo Display  

Type: class
Added by: bicycle
Entered: 26/08/2003
Last modified: 09/12/2002
Rating: - (fewer than 3 votes)
Views: 5601
Looks in any directory you specify and gets all the files with extensions given by you. Returns them as an array that you can do anything with, I used it to pick four photos from the photo album directory at random (sort of random) and display them in the footer of a page. Works around open_basedir restrictions.


<?

class filelist {

var 
$files;

// the class uses extensions like ("jpg","gif","png")
// the function prepends the document root, so 
// give directory information like "/images/album"

function GetList($directory,$ext FALSE) {
    
$files = array(); 
    
$handle opendir($_SERVER ['DOCUMENT_ROOT'].$directory);
    while(
false !== ($file readdir($handle))) {
        
//GET THE FILES ACCORDING TO THE EXTENSIONS ON THE ARRAY 
        
for ($i 0$i count($ext); $i++) {
            if (
eregi("."$ext[$i] ."$"$file)) {
                
$files[] = $file
            }
        }
    }
closedir($handle); 

$this->files $files;

}


function 
WriteList($dir,$ext FALSE) {
    
$this -> GetList($dir,$ext);
    foreach (
$this->files as $element) { 
        echo 
"$elementn"
    }
}

function 
WriteImages($dir,$ext FALSE) {
    
$this -> GetList($dir,$ext);
    
    
shuffle($this->files);
        
    for (
$i 0$i 4$i++) {
        
$element $this->files[$i];
        echo 
"<td><img src="$dir/$element" alt="Photo Album" height=147 border=0></td>n";
    }
}




}
?>


Usage Example


if (file_exists($_SERVER ['DOCUMENT_ROOT']."/global/classes/getfilelist.php")) {
        require_once($_SERVER ['DOCUMENT_ROOT'].'/global/classes/getfilelist.php');
        $exts = array("jpg","gif");
        $photo_dir = "/images/photoalbum/";
        $list = new filelist();
        $list->WriteImages($photo_dir,$exts);
    }


Rate This Script





Search



This Category All Categories