News Tutorials Projects Reviews Authors Contact Search Links Admin
 

Reading File Directories : Read and Output

Simple case

Reading file directories is very simple.

Try the following script out:

<?php
$handler = opendir('.');
while($file = readdir($handler)) {
	echo "$file<br>";
}
closedir($handler);
?>

What you will see is a list of all the files in the directory where the script is, including the script itself.

Notice . and ... These are special directory items. The . lists the current directory.
The .. lists the parent directory, the one below the current folder.

Basic filter

Infact, we want to filter . and .. out, because they can cause trouble. Hence:
<?php
$handler = opendir('.');
while($file = readdir($handler)) {
	if($file != '.' && $file != '..') {
		echo "$file<br>";
	}
}
closedir($handler);
?>

Identifying folders

We can add another filter to check if the $file is actually folder.
<?php
$handler = opendir('.');
while($file = readdir($handler)) {
	if(is_dir($file) && $file != '.' && $file != '..') {
		echo "<b>$file<br></b>";
	}
	elseif($file != '.' && $file != '..') {
		echo "$file<br>";
	}
}
closedir($handler);
?>

The function is_dir($file) checks to see if the given path is a folder, or not. Notice I included the . and .. in the if statement, to ensure they weren't filtered.

On the next page, read how to filter results to be more useful.

 


Author: Markavian
Last edited on: 22nd Jan, 9:14 am
Please rate this article.

« Prev page 'Useful functions' « » Next Page 'Useful Filters' »

tutorial Pages