Friday, April 15, 2011

Reading Files or Images from a Folder using PHP

<?
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($directory);
  while(false !== ($file = readdir($handle))) {
 
   //GET THE FILES ACCORDING TO THE EXTENSIONS ON THE ARRAY
 
   for ($i = 0; $i < count($ext); $i++) {
    if($ext and count($ext)) {
     if (eregi("\.". $ext[$i] ."$", $file)) {
      $files[] = $file;
     }
    } else {
     if($file != "." && $file != "..") {
      $files[] = $file;
     }
    }
   }
  }
  closedir($handle);
  $this->files = $files;
 }
 function WriteList($dir,$ext = FALSE) {
  $this->GetList($dir,$ext);
  foreach ($this->files as $element) {
   echo "$element\n";
  }
 }
 function WriteImages($dir,$ext = FALSE) {
  $this->GetList($dir,$ext);
  shuffle($this->files);
  //for ($i = 0; $i < 4; $i++) {
  foreach ($this->files as $element) {
   echo "<p><img src=\"$dir/$element\" alt=\"Photo Album\" height=147 border=0></p>\n";
  }
 }
}
// usage
$filelist= new filelist();
$ext = array("jpg", "gif", "png");
$filelist->WriteImages("C:\Documents and Settings\All Users\Documents\My Pictures\Sample Pictures", $ext);
?>

No comments:

Post a Comment