Directory handling in PHP

To read from a directory we firstly need to give the path name of the directory and check that we can open it.

if($dir = @opendir(getcwd()))

This example uses the getcwd function to return the path of the current directory (i.e. the one in which this code is placed). Now we need to loop through all the files and output them.

while ($files = @readdir($dir))

This loop gives the files variable the name of the next file in the directory. If there are no more then it will return false and stop the loop.

if(($files != '.') && ($files != '..') && ($files[0] != '.'))

The readdir function returns all files (and directories) so we will remove then ones that start with a period or are the period or double period respectively.

if(filetype($files) == 'dir')
   echo '<em><a href="'.$files.'">'.$files.'</a></em><br />';
   echo '<a href="'.$files.'">'.$files.'</a><br />';

To differentiate between files and directories we will output the directories with the em element by checking its type.


Finally we stop reading from the directory. If the initial read wasn’t successful we will alert the user.

   echo 'Directory can\'t be opened.';

To search for a particular file name or type you can use the glob function.

$php = glob('*.php');

The pattern entered above searches for all PHP documents in the current directory.