getButterfly Logo getButterfly

Method 1.

This is the simplest way to list files in a folder:

[php]
<?php
$dir = ".";
$dh = opendir($dir);
while (($file = readdir($dh)) !== false) {
echo $file.'<br />’;
}
closedir($dh);
?>
[/php]

In order to add links to the files in the folder, we modify the code as below. Warning, this might pose some serious security threats if publicly exposed.

[php]
<?php
$dir = ".";
$dh = opendir($dir);
while (($file = readdir($dh)) !== false) {
echo ‘<a href="’.$file.’">’.$file.'</a><br />’;
}
closedir($dh);
?>
[/php]

Method 2.

Another way to read the files would be:

[php]
<?php
$dir = ".";
$dh = opendir($dir);
$count=0;
while (($file = readdir($dh)) !== false) {
$count++;
if(substr($file,0,1) != ".") {
echo $file.'<br />’;
}
}
?>
[/php]

The line if(substr($file,0,1) != ".") ensures that no .htaccess or .htpasswd file will be read.

Method 3.

The third method of reading and linking files in a directory would be:

[php]
<?php
$current=getcwd();
$directory=basename($current);

$dir = ‘.’;
$dh = opendir($dir);
while (false !== ($filename = readdir($dh))) {
$files[] =$filename;
}
// let’s get rid of the ‘.’ and the ‘..’ parent and ancestor files
$t=array_slice($files,2);
// let’s get rid of the index.php file which does the reading
$f=array_search(‘index.php’,$t);
unset($t[$f]);

print(‘<a href=".">Back</a><br />’);
foreach($t as $key => $value) {
echo(‘<a href="’.$value.’">’.$value."</a><br />");
}
closedir($dh);
?>
[/php]

Method 4.

The fourth method is the shortest of them all:

[php]
<?php
$dir = ‘.’;
$files = scandir($dir);
//print_r($files);

$num = count($files);
for($n=0; $n<$num; $n++) {
echo $files[$n].'<br />’;
}
?>
[/php]

I left print_r($files); in place but commented in order to show the directory array.

Method 5.

This method resembles phpMyAdmin’s way of listing files with an icon for folders and files. Further customization could show all file types, such as images, archives, php files, html files, css files, and so on. Notice how the ls_recursive() function can be nicely tucked away in a functions file.

[php]
<?php
function ls_recursive2($dir) {
if(is_dir($dir)) {
$files = scandir($dir);
foreach ($files as $file) {
$currentfile = $dir."/".$file;
$last_dir = "";
$count = substr_count($currentfile, ‘/’);
$minus_count = substr_count($_SERVER[‘DOCUMENT_ROOT’], ‘/’);
$count -= ($minus_count + 2);

for($p = 0; $p<$count; $p++) {
$last_dir .= "&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;";
}

if(is_dir($currentfile)) {
if($file != ‘.’ && $file != ‘..’) {
$last_dir .= "<img src=’images/folder.gif’ alt=” align=’middle’ width=’16’ height=’16’ border=’0′>&nbsp;<a href=\"".$currentfile."\">".substr($currentfile, strrpos($currentfile, ‘/’))."</a><br />";
echo $last_dir;
ls_recursive2($currentfile);
}
}
else {
$last_dir .= "<img src=’images/file.gif’ alt=” align=’middle’ width=’16’ height=’16’ border=’0′>&nbsp;<a href=\"".$currentfile."\">".substr($currentfile, strrpos($currentfile, ‘/’))."</a><br />";
echo $last_dir;
}
}
}
}
ls_recursive2(‘.’);
?>
[/php]

Method 6.

Again a nice function for displaying both files in folders and files outside, a remake of the first method:

[php]
<?php
function listFolder($path) {
$dir_handle = opendir($path) or die("Unable to open $path");

$dirname = end(explode("/", $path));

echo ("<li>$dirname\n");
echo "<ul>\n";
while (false !== ($file = readdir($dir_handle))) {
if($file!="." && $file!="..") {
if(is_dir($path."/".$file)) {
listFolder($path."/".$file);
}
else {
echo "<li>$file</li>";
}
}
}
echo "</ul>\n";
echo "</li>\n";

closedir($dir_handle);
}
echo ‘<ul>’;
listFolder(‘.’);
echo ‘</ul>’;
?>
[/php]

Method 7.

Unlike the methods above, this one counts files of a certain extension (in this case, gifs):

[php]
<?php
$d = opendir(‘.’);
$count = 0;
while(($f = readdir($d)) !== false)
if(ereg(‘.gif$’, $f))
++$count;
closedir($d);
print "Files=$count";
?>
[/php]

Method 8.

This method shows how many files (not folders) are in a directory:

[php]
<?php
function num_files($directory) {
return count(glob($directory."*.*"));
}
echo num_files(”);
?>
[/php]

Method 9.

The ninth method adds an interesting feature, file upload. While reading the files in a folder, the script has the capacity to upload a new file in the current directory.

[php]
<?php
if (isset($_POST[‘submit’])) {
copy($_FILES[‘file’][‘tmp_name’], $_FILES[‘file’][‘name’]);
}

$dir=opendir(".");
$files=array();
while (($file=readdir($dir)) !== false) {
if($file != "." and $file != ".." and $file != "index.php") {
array_push($files, $file);
}
}
closedir($dir);
sort($files);

foreach ($files as $file)
print "<a href=’$file’>$file</a><br />";
?>
[/php]

[xhtml]
<form action="<?php echo $PHP_SELF ?>" enctype="multipart/form-data" method="POST">
Add a new file: <input type="file" name="file" />
<input type="submit" name="submit" value="Upload file">
</form>
[/xhtml]

That’s all!

Notice that all examples use ‘.’, which means the curent directory. By using ‘/’ these functions would scan the parent directory.


Subscribe to getButterfly Blog

Once a week or so we send an email with our best content. We never bug you, we just send you our latest piece of content.



If you found any value in this post, agree, disagree, or have anything to add - please do. I use comments as my #1 signal for what to write about. Read our comment policy before commenting! Comments such as "Thank you!", "Awesome!", "You're the man!" are either marked as spam or stripped from URL.

3 thoughts on “9 Methods To Read Files In A Folder Using PHP

Leave a reply