Full code - directory.php

<?php
if($dir = @opendir(getcwd()))
{
	while ($files = @readdir($dir))
	{
		if(($files != '.') && ($files != '..') && ($files[0] != '.'))
		{
			if(filetype($files) == 'dir')
				echo '<em><a href="'.$files.'">'.$files.'</a></em><br />';
			else
…

Download the code »

Tutorial

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 />';
else
   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.

closedir($dir);

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

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

Full code - directory2.php

<?php
$php = glob('*.php');
$count = count($php);

foreach($php as $file)
	echo $file.'<br />';

echo $count.' files';
?>

Download the code »

Searching a directory

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.

Adobe Fireworks® Adobe Flash® and Adobe Photoshop® are either registered trademarks or trademarks of Adobe Systems Incorporated in the United States and/or other countries.
MySQL is a registered trademark of MySQL AB in the United States, the European Union and other countries.
Copyright Pixelcode 2005 - 2010