Tutorials PHP Looping Files in a Folder

Looping Files in a Folder

Today you will learn how to use PHP to load files from a folder. If you have something like a bunch of images or documents in a folder that you just want to throw up on the page, this becomes really handy.

How do I open a folder and loop files?

// select folder
$docs_directory = "folder";

// open folder
$dir_handle = opendir($docs_directory) or die("There is an error with your folder");

// loop through files
while ($file = readdir($dir_handle)){

  echo 'File: '.$file.'<br/>';
  
}; // close while loop

// close the folder
closedir($dir_handle);

How do I filter results?

So lets say you have a bunch of files in your folder but you only wanted to display image files.

// select folder
$docs_directory = "folder";

// allowed file extension
$allowed_types = array('jpg','png','gif');

// open folder
$dir_handle = opendir($docs_directory) or die("There is an error with your folder");

// loop through files
while ($file = readdir($dir_handle)){

  // breaks the file into an array
  $file_parts = explode('.',$file);
  
  // breaks off the extension
  $ext = array_pop($file_parts);
  
  // determine if extension is allowed
  if(in_array($ext,$allowed_types)) {
    echo 'File: '.$file.'<br/>';
  }
}; // close while loop

// close the folder
closedir($dir_handle);

Posted by on . Category: PHP


Comments

No comments posted yet

You need to register or login to post new comments.