How to recursively read the contents of a directory and subdirectories in PHP

Downloads:353 Bookmark this code Bookmark and Share
Rank : 2.33/5
Rated by : 3 user(s)
Developer:Andrew R  |   13 submission(s)
Date Uploaded:November 01,2009
Level:Intermediate
Size: 0 Bytes
Category:PHP -> Files
Developer Says:

This sample code is a function that recursively read the contents of a directory and subdirectories. The directory is highlighted with an H2 tag

<?
/*
* This sample code is a function that recursively read the contents of a directory and subdirectories. The directory is highlighted with an H2 tag
*/
function read_dir($dir) {
   $array = array();
   $array[]='<h2>'.$dir.'</h2>';
   $d = dir($dir);
   while (false !== ($entry = $d->read())) {
	   $status='';
       if($entry!='.' && $entry!='..') {
           $entry = $dir.'/'.$entry;
           if(is_dir($entry)) {
               $array = array_merge($array, read_dir($entry));
           } else {
               $array[] = $entry;
           }
       }
   }
   $d->close();
   return $array;
}
 
 ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Recursively reading the content of a directory and subdirectories in PHP</title>
</head>

<body style="font-family:tahoma; font-size:11px; color:#333;">
    <pre>
    <?
        print_r(read_dir(dirname($_SERVER['SCRIPT_FILENAME'])));
    ?>
    </pre>
</body>
</html>

The above code was highlighted with Neat Highlighter


User Reviews
There are no user reviews on this code
Leave a Comment
Age (Required, will not be shown)
Name
Email (Required, will not be shown)
Website (Optional, starting with http://)
 
Rate this code
Poor   1 2 3 4 5   Outstanding
Are you human ?

Enter the code shown above