PHP MySQL Tutorial
Learn PHP and MySQL

List a Directory's Contents Using PHP

List a Directory's Contents Using PHP

To list the content of a directory you just need to use the combination of opendir() and readdir() functions.

// directory path can be either absolute or relative
$dirPath = '.';

// open the specified directory and check if it's opened successfully
if ($handle = opendir($dirPath)) {

   // keep reading the directory entries 'til the end
   while (false !== ($file = readdir($handle))) {

      // just skip the reference to current and parent directory
      if ($file != "." && $file != "..") {
         if (is_dir("$dirPath/$file")) {
            // found a directory, do something with it?
            echo "[$file]<br>";
         } else {
            // found an ordinary file
            echo "$file<br>";
         }
      }
   }

   // ALWAYS remember to close what you opened
   closedir($handle);
}


When you list the files surely you need to know which of these files are actually a sub-directory. Using the is_dir() function you can test if the files is really a directory or not. What you want to do later with that directory is up to you. On the code above directories are simply printed in a square brackets to differentiate them with ordinary files

Recent Comments

By: Kervin Gabilo Posted on 01-05-2009 8:29 AM
100% of people found this useful

I have created my own version for this topic based from the codes above.

It has breadcrumbs that you can click (the ones like the vista navigation.

hope this one helps.

there are also icons based from the file's extensions.

hope this helps....

<pre>

<?

//default directory when the text field has no input

$def='C:/';

// directory path can be either absolute or relative

function lister($dirPath){

// open the specified directory and check if it's opened successfully

if ($handle=opendir($dirPath)) {

// keep reading the directory entries 'til the end

while (false !== ($file = readdir($handle))) {

// just skip the reference to current and parent directory

if ($file != "." && $file != "..") {

if (is_dir("$dirPath/$file")) {

// found a directory, do something with it?

echo '<img src="icons/f.png"/>  <a href="#" onclick="javascript: r(\''.$dirPath.$file.'/\'); d()">'.$file.'</a><br/>';

} else {

// found an ordinary file

$extensions=array('a','abr','acb','aco','act','acv','ado','ai','ani','asl','atn','blw','bmp','bz2','c','cha','chm','csh','css','csv','cur','c~','db','dll','doc','docx','dot','exe','exv','f','gif','grd','gz','htm','html','ico','ima','inf','ini','irons','irs','jpeg','jpg','js','jsx','kys','logo','mbr','mid','mnu','mp3','msi','mus','mxp','pat','pdf','php','png','psd','rar','reg','rtf','shc','sql','swf','tpl','ttf','txt','txt~','xls','xpi','zip','zvt','wma','mpg');

$ext=$file;

$pos=strrpos($ext,'.');

$ext=substr(substr($ext,$pos),1);

if(in_array(strtolower($ext),$extensions)){

echo '<img src="icons/'.$ext.'.png"/>  '.$file.'<br/>';

}else{

echo '<img src="icons/a.png"/>  '.$file.'<br/>';

}

}

}

}

// ALWAYS remember to close what you opened

closedir($handle);

}

}

?>

<html>

<head>

<title>List Contents</title>

<link rel="icon" href="icons/logo.png"/>

<link rel="stylesheet" href="style.css"/>

<script type="text/javascript">

function r(dir){

document.lister.directory.value=dir;

}

function d(){

document.lister.submit();

}

</script>

</head>

<body><br/>

<table class="cells"><tr>

<td class="navi">

<div class="container">

<form method="post" autocomplete="off" name="lister">

Directory:<br/>

<input type="text" name="directory"/><br/><br/>

<input type="submit" name="list" value="LIST"/>

</form>

<br/><br/>

</div>

</td>

<td class="content">

You are currently at:<br/>

<div class="breadcrumbs" id="crum">

<?php

#show the breadscrumbs so as to navigate to the last directory.

$path=explode('/',$_POST['directory']);

$it=count($path);

for($i=1;$i<$it;$i++){

echo '<a href="#" onclick="r(\'';

for($j=0;$j<$i;$j++){

echo $path[$j].'/';

}

echo '\'); d();">';

echo '<font color=red>'.$path[$i-1].'</font>';

echo '</a><img src="icons/a.png"/>';

}

?>

</div>

address: <input type="text" style="height: 16px; width: 600px;" value="<?=$_POST['directory']?>"/>

<br/>

<br/>

<?php

if($_POST['directory']==''){

lister($def);

}else{

lister($_POST['directory']);

}

?>

</td>

</tr></table>

</body>

</html>

</pre>

By: Dan Posted on 05-06-2009 1:47 PM

I'm fairly new to php, will this recursively list all the directories and files within a given location?

Recursive loops are quite difficult to manage in my experience, I had to use an array which I had to re-reserve memory for every time it ran the code.

By: dwainehead Posted on 05-22-2009 11:59 AM

thiere's also a simpler way then the above codes and wise person showed me while I was having problems listing images dynamicaly from a folder to be included in a javascript slideshow.

the code below can be modifed for what ever files types your needs are

$imgs = glob('images/*.{gif,jpg,jpe,jpeg,png}', GLOB_BRACE);

foreach($imgs as $key =" $val)

$imgs[$key] = '<img src="'.$val.'" title="'.$key.'">';

print $imgs;

By: TigerDragon Posted on 10-02-2009 5:23 PM

Hello All,

My code is very similar to the original poster. A minor differences on logic and with the commands use, plus I only list *.pdf files but I think it doesn't matter. What bothers me is, the code is being ran on WinXP Pro and on Ubuntu Server. On XP, files are listed alphabetically in order (which is perfect) but on Ubuntu, files are listed random. And I dont know why, Am I missing something on PHP or do I need to configure ubuntu? puzzles me.

I issued a command "dir" and "ls -l or ls -al" on ubuntu prompt and found that both command list it alphabetically. --> confuses me more

Thinking a work around... I can modify PHP to save it to array then sort it before displaying, but not willing to that (yet) if I only miss something very minor. Plus my ubuntu sever has lot more than files than my XP which I believe will be running slower if I do that.

I'm no PHP expert nor linux and needed someone who can point me to right direction.  I just dont know where to start. Any comments by Linux experts??? or comments by PHP experts.

if it matters. i use UBUNTU 8.04 and just updated to PHP 5.2.4 (i guess)

Thank you in advance.

TD

By: TigerDragon Posted on 10-02-2009 5:53 PM

For your reference, heres the PHP portion

<? $path = "/var/www/datasheets/"; //Only difference with the XP version

$itemsNo = 0;

$DirHandler = opendir($path) or die("Unauthorize Access");

print("<td width =\"100%\"><div align=\"center\">");

print("<table border=1 cellpadding=5 cellspacing=0 class=whitelinks>");

print("<tr bgcolor=\"FF0F0F\" ><th>Item No.</th><th>File</th><th>Filesize</th></tr>");

while ($file = readdir($DirHandler)) {

if  (($file !="index.php") && (substr("$file", 0, 1) != ".")) {

$itemNo++;

$ModelNo = substr("$file",0,strlen($file) - 4);

print("<tr><td align=\"center\">$itemNo</td>");;

print("<td><b><a href=\"$file\">$ModelNo</a></b></td>");

print("<td>");

$dispsize = filesize($file);

$UnitSize = " Bytes";

if ($dispSize >= 1000000) {

$dispsize = $dispsize/1000000;

$UnitSize = " MB";

}

if ($dispSize >= 1000) {

$dispsize = $dispsize/1000;

$UnitSize = " KB";

}

print($dispSize));

print($UnitSize);

print("</td></TR>");

}

print("</div></td>");

}

closedir($DirHandler);

?>

I temporary drop the index.php here --> www.johnlauder.com/projects  (this is running under WinXP, the ubuntu is plainly internal)

thanks again.

jL aka TD

Powered by Community Server (Non-Commercial Edition), by Telligent Systems