Display Styled Directory Contents

Servers can be configured to show the contents of a directory that doesn't have an index file to render. The result is usually less than visually spectacular:

Lackluster default in Chrome

More better, View Demo

We can take control of this ourselves by replicating this functionality with PHP.

  1. Make an index file (.index.php, starting with the dot, really) which reads the files in the directory and outputs them into a table
  2. Make an .htaccess file that serves that file as the index
  3. Have the index file load in CSS and other resources that are also prefixed with a dot (hidden)

The following PHP reads the directory of files and displays a styled table of their name, file type, and file size. It also applies a class name in which to apply icons for the different major file types (see CSS).

<!doctype html>
<html>

<head>
  <meta charset="UTF-8">
  <title>Directory Contents</title>
  <link rel="stylesheet" href=".style.css">
  <script src=".sorttable.js"></script>
</head>

<body>

  <div id="container">
  
    <h1>Directory Contents</h1>
    
    <table class="sortable">
      <thead>
        <tr>
          <th>Filename</th>
          <th>Type</th>
          <th>Size <small>(bytes)</small></th>
          <th>Date Modified</th>
        </tr>
      </thead>
      <tbody>
      <?php
        // Opens directory
        $myDirectory=opendir(".");
        
        // Gets each entry
        while($entryName=readdir($myDirectory)) {
          $dirArray[]=$entryName;
        }
        
        // Finds extensions of files
        function findexts ($filename) {
          $filename=strtolower($filename);
          $exts=split("[/\\.]", $filename);
          $n=count($exts)-1;
          $exts=$exts[$n];
          return $exts;
        }
        
        // Closes directory
        closedir($myDirectory);
        
        // Counts elements in array
        $indexCount=count($dirArray);
        
        // Sorts files
        sort($dirArray);
        
        // Loops through the array of files
        for($index=0; $index < $indexCount; $index++) {
        
          // Allows ./?hidden to show hidden files
          if($_SERVER['QUERY_STRING']=="hidden")
          {$hide="";
          $ahref="./";
          $atext="Hide";}
          else
          {$hide=".";
          $ahref="./?hidden";
          $atext="Show";}
          if(substr("$dirArray[$index]", 0, 1) != $hide) {
          
          // Gets File Names
          $name=$dirArray[$index];
          $namehref=$dirArray[$index];
          
          // Gets Extensions 
          $extn=findexts($dirArray[$index]); 
          
          // Gets file size 
          $size=number_format(filesize($dirArray[$index]));
          
          // Gets Date Modified Data
          $modtime=date("M j Y g:i A", filemtime($dirArray[$index]));
          $timekey=date("YmdHis", filemtime($dirArray[$index]));
          
          // Prettifies File Types, add more to suit your needs.
          switch ($extn){
            case "png": $extn="PNG Image"; break;
            case "jpg": $extn="JPEG Image"; break;
            case "svg": $extn="SVG Image"; break;
            case "gif": $extn="GIF Image"; break;
            case "ico": $extn="Windows Icon"; break;
            
            case "txt": $extn="Text File"; break;
            case "log": $extn="Log File"; break;
            case "htm": $extn="HTML File"; break;
            case "php": $extn="PHP Script"; break;
            case "js": $extn="Javascript"; break;
            case "css": $extn="Stylesheet"; break;
            case "pdf": $extn="PDF Document"; break;
            
            case "zip": $extn="ZIP Archive"; break;
            case "bak": $extn="Backup File"; break;
            
            default: $extn=strtoupper($extn)." File"; break;
          }
          
          // Separates directories
          if(is_dir($dirArray[$index])) {
            $extn="&lt;Directory&gt;"; 
            $size="&lt;Directory&gt;"; 
            $class="dir";
          } else {
            $class="file";
          }
          
          // Cleans up . and .. directories 
          if($name=="."){$name=". (Current Directory)"; $extn="&lt;System Dir&gt;";}
          if($name==".."){$name=".. (Parent Directory)"; $extn="&lt;System Dir&gt;";}
          
          // Print 'em
          print("
          <tr class='$class'>
            <td><a href='./$namehref'>$name</a></td>
            <td><a href='./$namehref'>$extn</a></td>
            <td><a href='./$namehref'>$size</a></td>
            <td sorttable_customkey='$timekey'><a href='./$namehref'>$modtime</a></td>
          </tr>");
          }
        }
      ?>
      </tbody>
    </table>
  
    <h2><?php print("<a href='$ahref'>$atext hidden files</a>"); ?></h2>
    
  </div>
  
</body>

</html>

The resources loaded in that index file are the top-in table sorter script sortable.js and a .style.css file. (Remember, prefacing the files with a dot makes the invisible in most operating systems, and also won't show up in your directory of files (good)). Here's that CSS:

* {
	padding:0;
	margin:0;
}

body {
	color: #333;
	font: 14px Sans-Serif;
	padding: 50px;
	background: #eee;
}

h1 {
	text-align: center;
	padding: 20px 0 12px 0;
	margin: 0;
}
h2 {
	font-size: 16px;
	text-align: center;
	padding: 0 0 12px 0; 
}

#container {
	box-shadow: 0 5px 10px -5px rgba(0,0,0,0.5);
	position: relative;
	background: white; 
}

table {
	background-color: #F3F3F3;
	border-collapse: collapse;
	width: 100%;
	margin: 15px 0;
}

th {
	background-color: #FE4902;
	color: #FFF;
	cursor: pointer;
	padding: 5px 10px;
}

th small {
	font-size: 9px; 
}

td, th {
	text-align: left;
}

a {
	text-decoration: none;
}

td a {
	color: #663300;
	display: block;
	padding: 5px 10px;
}
th a {
	padding-left: 0
}

td:first-of-type a {
	background: url(./.images/file.png) no-repeat 10px 50%;
	padding-left: 35px;
}
th:first-of-type {
	padding-left: 35px;
}

td:not(:first-of-type) a {
	background-image: none !important;
} 

tr:nth-of-type(odd) {
	background-color: #E6E6E6;
}

tr:hover td {
	background-color:#CACACA;
}

tr:hover td a {
	color: #000;
}





/* icons for file types (icons by famfamfam) */

/* images */
table tr td:first-of-type a[href$=".jpg"], 
table tr td:first-of-type a[href$=".png"], 
table tr td:first-of-type a[href$=".gif"], 
table tr td:first-of-type a[href$=".svg"], 
table tr td:first-of-type a[href$=".jpeg"]
{background-image: url(./.images/image.png);}

/* zips */
table tr td:first-of-type a[href$=".zip"] 
{background-image: url(./.images/zip.png);}

/* css */
table tr td:first-of-type a[href$=".css"] 
{background-image: url(./.images/css.png);}

/* docs */
table tr td:first-of-type a[href$=".doc"],
table tr td:first-of-type a[href$=".docx"],
table tr td:first-of-type a[href$=".ppt"],
table tr td:first-of-type a[href$=".pptx"],
table tr td:first-of-type a[href$=".pps"],
table tr td:first-of-type a[href$=".ppsx"],
table tr td:first-of-type a[href$=".xls"],
table tr td:first-of-type a[href$=".xlsx"]
{background-image: url(./.images/office.png)}

/* videos */
table tr td:first-of-type a[href$=".avi"], 
table tr td:first-of-type a[href$=".wmv"], 
table tr td:first-of-type a[href$=".mp4"], 
table tr td:first-of-type a[href$=".mov"], 
table tr td:first-of-type a[href$=".m4a"]
{background-image: url(./.images/video.png);}

/* audio */
table tr td:first-of-type a[href$=".mp3"], 
table tr td:first-of-type a[href$=".ogg"], 
table tr td:first-of-type a[href$=".aac"], 
table tr td:first-of-type a[href$=".wma"] 
{background-image: url(./.images/audio.png);}

/* web pages */
table tr td:first-of-type a[href$=".html"],
table tr td:first-of-type a[href$=".htm"],
table tr td:first-of-type a[href$=".xml"]
{background-image: url(./.images/xml.png);}

table tr td:first-of-type a[href$=".php"] 
{background-image: url(./.images/php.png);}

table tr td:first-of-type a[href$=".js"] 
{background-image: url(./.images/script.png);}

/* directories */
table tr.dir td:first-of-type a
{background-image: url(./.images/folder.png);}

View Demo   Download Files

REMEMBER: The .zip file might appear to be empty, but it's not. The files are all prefaced with a dot. View them in a file editor which shows you "hidden" files.

Special thanks to Cliff White.

Update November 2012: The demo and downloadable files have been updated to 1) show more human readable file sizes 2) have error pages

Comments

  1. User Avatar
    Thomas J
    Permalink to comment#

    You need to change line 136 to this to avoid a Parse error.

    a href='$dirArray[$index]'

    After that this works perfect! Thanks for sharing!

    //T

    • User Avatar
      Chris Coyier
      Permalink to comment#

      There were \” marks in there to make sure that wasn’t a problem but for whatever reason weren’t showing up in the displayed code. I just made them single ticks to avoid problems, thanks!

    • User Avatar
      ppahppp
      Permalink to comment#

      It worked for me when i renamed .index.php to index.php removing the dot. Not sure why my server didint pick up what to do from the htaccess file

    • User Avatar
      Toji K Dominic
      Permalink to comment#

      @ppahppp You need to enable .htaccess functionality in your apache server.
      Make AllowOverride None to AllowOverride All just like shown below and restart apache.

      AllowOverride All

  2. User Avatar
    Thad Bloom
    Permalink to comment#

    Very nice script, thanks for sharing!

  3. User Avatar
    Mike Smith
    Permalink to comment#

    nice script. I’m sure I can find something to use this for :)

  4. User Avatar
    Steven Rossi
    Permalink to comment#

    Looks really cool – I’ll definitely be using this for something or other.

  5. User Avatar
    kenaku
    Permalink to comment#

    sweet. and so simple. thanks!

  6. User Avatar
    fabuio
    Permalink to comment#

    Nice. Thanks.

    line 141:
    print(number_format((filesize($dirArray[$index])), 0, ”, ‘,’));

  7. User Avatar
    Aziz Light
    Permalink to comment#

    Nice!

    One thing though: where can I find the little icons on the left of the file/folder please?

    • User Avatar
      Andrew Champ
      Permalink to comment#

      Here are the icons I used, they’re great for everything!

      http://www.famfamfam.com/lab/icons/

    • User Avatar
      James Boblak
      Permalink to comment#

      The image for audio.png is incorrectly named sound.png – or the image sound.png is incorrectly called out as audio.png in the .style.css script! Also, I added:

      table tr td:first-of-type a[href$=”.wav”],

      to the list of sound file types, and it worked on my .wav’s too 8)

  8. User Avatar
    Mark, eLearning Designer
    Permalink to comment#

    Thanks for this. This is a great bit of code and very easy to add even for a php newb like me.

  9. User Avatar
    Maggie Wolfe Riley
    Permalink to comment#

    I’m getting an error from this line: print(filesize($dirArray[$index]));
    I think it’s line 141 in the original, but I am just using the php part as an include with my own CSS so it’s line 48 in mine. Here is the error:

    Warning: filesize() [function.filesize]: stat failed for archives in /..(path to my website).org/includes/directory_contents.php on line 48

    I believe the error is because it is printing out the parent directory folder (and its parent, too), which have no filesize. It works great, except for those two lines – and I can’t figure out why they even are being printed, since they are not files IN the directory… My folder structure is /newsletters/archives/index.php and the first row of the table displaying the files shows “archives,” with the error under the filesize column, and the last row of the table shows “newsletters” and another filesize error.

    I’m just learning PHP, but I think a line to set the condition if there is no suffix, don’t include it might be fairly easy… for someone who is more fluent in PHP, anyway :)

    Anyone have any ideas? Thanks!

    • User Avatar
      Maggie Wolfe Riley
      Permalink to comment#

      I’m trying to figure it out, but realized that setting a condition for not printing a file without a “.” in the string won’t work, because the “files” that are causing the errors don’t actually exist – it’s showing the parent and “grandparent” directories as if they were files IN the directory – /newsletters/archives/archives and /newsletters/archives/newsletters

      I can’t figure out what is causing that, and since they don’t actually exist in the directory, my idea for setting a condition of not printing a string without a “.” in it won’t have any effect. And it hasn’t.

      Here’s the page:
      http://bristleconecnps.org/newsletters/archives/index.php

  10. User Avatar
    Maggie Wolfe Riley
    Permalink to comment#

    I got it to stop displaying the empty line at the top and the first error – the archives one, by changing the loop to this:

    for($index=4; $index < $indexCount; $index++) {

    starting at “1” instead of 0 got rid of the blank, and starting at “4” takes into consideration the two parent directories which aren’t being shown plus the weird error one, and starts on the first real file. There is still the error at the end (last row) of the table.

    Okay, my head hurts, and I hope some of you wonderful PHP people and problem solvers have some better ideas!

    Thanks.

    • User Avatar
      Maggie Wolfe Riley
      Permalink to comment#

      I just fixed it:
      for($index=4; $index < $indexCount-1; $index++) {
      (added -1 to the index count so it wouldn’t show the last “file”)

      This is obviously a workaround that is specific to that file structure – if the directory was at a different level it would need to start at a different place, which makes using this code as an include for any directory index file I want on my site not as simple, but hey, it works!

      Sorry for all the multiple comment posts, but I hope it may be helpful and/or interesting to someone! :)

      And if someone has a better idea that will fix it instead of hiding it, I would love to hear it.

      Thanks!!

    • User Avatar
      Laurent Jouvin
      Permalink to comment#

      This will prevent the last file from being listed in the directory. Do you have any idea on how to prevent the index.php from showing?

    • User Avatar
      cnwtx
      Permalink to comment#

      Put this line in your .htaccess file:

      DirectoryIndex  index.html index.htm default.htm index.php .index.php 

      Then rename the file to .index.php (with the leading dot). The php script script will then prevent the showing of hidden files. The result: your index.php will not show up in the listings.

  11. User Avatar
    Laurent Jouvin
    Permalink to comment#

    Very cool. Thank you very much Chris. I know I’m late in the game here but I’m definitely gonna use your script.

  12. User Avatar
    Laurent Jouvin
    Permalink to comment#

    OK… I’ve played with this and it works great. Really excited about this but I don’t know enough to start adding stuff to the code. But what about adding a download function to the directory? Each of the items would get their own download button. Just an idea in case someone would like to try it. Thanks again for the script!

  13. User Avatar
    Chris
    Permalink to comment#

    Hey this is great code works so sweet!

    But I need to open up a different dir to where the script is located how do i do that?

  14. User Avatar
    Tom S
    Permalink to comment#

    Cannot get this to work. It only displays the headers on my page… no file listings, and there are plenty of files in the directory.

    Any thoughts?

    • User Avatar
      Zeyad
      Permalink to comment#

      Dear all :
      You can choose a certain file only , for example if you want to display “.doc” only without any files maybe exist in that folder, so then you should REPLACE this code instead of gets each entry to be seems as follow:

      // gets each entry
      while($entryName = readdir($myDirectory)) {
      if (strpos($entryName, ‘.doc’,1) ) {
      $dirArray[] = $entryName;
      }
      }

      Zeyad

  15. User Avatar
    David
    Permalink to comment#

    Anyone know how to get it to NOT display certain given files such as the favicon or the index.php file?

    Better still for me: how do i make display ONLY the folder names?

    Useful script. Thanks.

    David

    • User Avatar
      Benjamin
      Permalink to comment#

      Hi David,

      I had a closer look at this script, very useful indeed… my suggestion for you are:

      Define (just before the while-loop): $forbiddenExts = array(“php”, “ico”, “html”);
      In the while-loop, do the same as in findexts():

      while($entryName = readdir($myDirectory)) { 
      $exts = explode(".", $entryName);
        if(!in_array($exts[1],$forbiddenExts)) { 
          $dirArray[] = $entryName;
        }
      }

      And if you want to display only folders, then add another line of code just before the first if:

      if (!is_file($entryName)) {
      // the lines above
      }

      Altogether:

      
      // opens this directory
      			$myDirectory = opendir(".");
      			
      			// set forbidden files
      			$forbiddenExts = array("php", "ico", "html");
      			
      			// gets each entry
      			while($entryName = readdir($myDirectory)) {
      				if (is_file($entryName)) {
      					$exts = explode(".", $entryName);
      					if(!in_array($exts[1],$forbiddenExts)) { 
      						$dirArray[] = $entryName;
      					}
      				}
      			}
      
    • User Avatar
      Benjamin
      Permalink to comment#

      !is_file()… you don’t want to display files… in my script I don’t want to display folders… ;-)

    • User Avatar
      CJ
      Permalink to comment#

      @Benjamin – I’m stumped. I only want to display folders, so I used your additional script and get “Notice: Undefined offset: 1 in…” for every folder displayed (so, in my case, 5 Notices).

      I think this is referring to the section of code that reads:
      if(!in_array($exts[1],$forbiddenExts))

      Suggestions?

  16. User Avatar
    heath
    Permalink to comment#

    great script, but i can’t figure out how i can change the folder.
    every time i change the directory there will appear a mistake in that in in which sort($dirArray); located.

    what i’m supposed to do?

  17. User Avatar
    Justin Cilliers
    Permalink to comment#

    just another method i have used before, which displays the contents of a folder, and gives a link and preview… if anybody wants the code, let me know. example is http://www.inktecbots.com/specials.php

  18. User Avatar
    jassi
    Permalink to comment#

    hi..
    i m just learning to use php… this code is gr8…
    i m getting the parse error… so what is the change in line 136?
    thanx

  19. User Avatar
    jon
    Permalink to comment#

    hey, im getting this to work really well, but what if i wanted to display folders and files, but excluding the php and icon files? what would i need to change?

  20. User Avatar
    jon
    Permalink to comment#

    right…but in some instances i want it to display both files AND folder, but NOT the *.ico and *.php files

  21. User Avatar
    Rafael Trabasso
    Permalink to comment#

    Life. Saver.
    I have customized the script to create a simple with links from given folders. You don’t know how this helped me out, thanks a lot.

  22. User Avatar
    Prad

    Thanks buddy! helped me a lot

  23. User Avatar
    Martin
    Permalink to comment#

    if one chances the line $myDirectory line to:

    $myDirectory = opendir(“c:\docs”);

    The files in the docs directory are listed correctly, however, when one clicks on the link the link ties to load the file from the localhost directory.

    Is there an easy way of linking to the the files in the c:\docs directory?

    Thanks

  24. User Avatar
    Gokul
    Permalink to comment#

    Thanks for this piece of code. Cute one

  25. User Avatar
    Akhilaa
    Permalink to comment#

    Im learner for php. This code show some error. the extenson of this file is .php rite?

  26. User Avatar
    Akhilaa
    Permalink to comment#

    excatly wht my requirement is to dispaly the file in particular local folder in webpage…. so tht clicking on the links the file shuld get downloaded….. pls can anyone help me in doin this?. i need in html

  27. User Avatar
    Brian
    Permalink to comment#

    This is not working for me. I used it as it is in php 5 but i is not working at all. what should I modify?

  28. User Avatar
    Jack
    Permalink to comment#

    I’m having an issue displaying the file size when I change the directory.

    http://infasyssolutions.com/control.php

    Above is what I’m trying to make work. If i leave it to the (“.”) everything works perfect, but when I change it to (“images”) everything but the file size works. Any ideas as to why?

  29. User Avatar
    Ann Rose
    Permalink to comment#

    Hai.. this code helps me alot..
    but i need to listout folders in the directory and also if there is any documents in that folder that also should be listout..please help me

  30. User Avatar
    Jonathan
    Permalink to comment#

    I found a fix the issue with changing the directory.
    The problem was that changing the directory prevented the hyperlink to the file from working, along with preventing the PHP processor from accessing the file to read its size. Even though it still listed the files in the folder as intended.
    Do the following:
    ————————————————————————–
    *Replace the lines:

    
    // opens this directory
    $myDirectory = opendir(".");
    

    with the lines:

    
    $directory = "./";  // or example: $directory = "uploads/";
    // opens this directory
    $myDirectory = opendir($directory);
    

    ————————————————————————–
    Also replace:

    
    $exts = split("[/\\.]", $filename) ;

    with

    
    $exts = split("[/\\.]", $filename) ;
    //$exts = explode("[/\\.]", $filename) ;

    You may need to use if you version of PHP is 5.3 or later.
    ————————————————————————–
    Replace:

    
    <a href='$dirArray[$index]'

    with:

    
    <a href='$directory$dirArray[$index]'

    ————————————————————————–
    and replace:

    
    filesize($dirArray[$index])

    with

    
    filesize($directory.$dirArray[$index])
    • User Avatar
      Naema
      Permalink to comment#

      Thank you so much, Jonathan! I’ve was stumped by the directory issues and your comments worked like magic!

  31. User Avatar
    Haakon and Aase
    Permalink to comment#

    We would like to thank you for the great script you have made. Specially the thing with transperent effeect. It’s one of the coolest thing on earth.

  32. User Avatar
    Rolland
    Permalink to comment#

    Is there any way to load a directory from an external domain?

  33. User Avatar
    Jeff
    Permalink to comment#

    Great piece of work which no doubt will help many people.
    I also found the reworking of the script to show the contents of a different folder/location to be very helpful as it overcomes the problems of showing certain file types which you may not otherwise wish to make viewable.
    I did however find one small issue after the rework in as much as the icons for the file types weren’t displaying in the directory listing … and in my case, having put the icons in a folder called ‘img’ I simply had to change the following lines 60 through to 89 …

    I’ll only give one example to save space :

    71 /*docs*/
    72 a[href$=”.doc”] {background: url(img/doc.gif) no-repeat left 50%;}
    73 a[href$=”.txt”] {background: url(img/doc.gif) no-repeat left 50%;}
    74 a[href$=”.rtf”] {background: url(img/doc.gif) no-repeat left 50%;}

    I hope this helps … even just one person …

    Anyway … MAGNIFICENT script … MANY THANKS ;-)

  34. User Avatar
    atarubi
    Permalink to comment#

    To get filesize of a file from another directory :

    $dirname = "./YourFolderName" //Change "YourFolderName" to your folder's name
    $filez = $dirArray[$index]; //Get the name of file
    $path = $dir.'/'.$filen; //Path address of the file (included the directory path)
    $size = filesize($path); //Get the size of a file
    print("$size"); //print the size

    I use PHP 5.2.10, it works fine .

  35. User Avatar
    Simon Cleaver
    Permalink to comment#

    HI, very nice script – thanks a lot.
    I have created a page that shows the latest pdf on my web using google docs viewer.
    Could the code be added to the script, so that a “view online” link is added to the file list?

    The code I´m using is as follows:
    ” iframe src=”http://docs.google.com/gview?url=http://www.benitezjones.com/uploads/ultima.pdf&embedded=true” style=”width:718px; height:700px;” frameborder=”0″

    Any ideas?

  36. User Avatar
    Jesus
    Permalink to comment#

    How to display the last modified date?

    • User Avatar
      cnwtx
      Permalink to comment#

      Add this line inside the while loop:

      $modtime=date("M j Y g:i A", filemtime($dirArray[$index]));

      And then this wherever you want to output that time (still must be inside the loop):

      print("$modtime");
  37. User Avatar
    Jessica
    Permalink to comment#

    How do you also create a css archive by adding thumbnail using first image and excerpt of a file.

  38. User Avatar
    Zeyad
    Permalink to comment#

    Dear All;
    thanks Jesus
    if body can help that question
    How to display the last modified date
    ————————————————–

    Question to Help :

    How to display results in limit for 30 results per page – infact this to large reults inside same folder
    any help
    please

  39. User Avatar
    Joel
    Permalink to comment#

    Thanks a lot. Looking everywhere for one of these that worked, this code is perfect. Appreciate your addition to hide specific file types as well. Exactly what I needed.

  40. User Avatar
    Zeyad
    Permalink to comment#

    How to display results in limit for 30 results per page – infact this to large reults inside same folder
    any help
    please

  41. User Avatar
    Bud F
    Permalink to comment#

    Is there a way to mark the directories in that directory as such.I use words ,letters and it would be helpful if they were marked somehow.This is the best Script of this type I have found.I have looked high and low for this and came across this purely by accident.Thanks Andrew for posting this for others to use

  42. User Avatar
    Zeyad
    Permalink to comment#

    Dear all :
    You can choose a certain file only , for example if you want to display “.doc” only without any files maybe exist in that folder, so then you should REPLACE this code instead of gets each entry to be seems as follow:

    // gets each entry
    while($entryName = readdir($myDirectory)) {
    if (strpos($entryName, ‘.mp3’,1) ) {
    $dirArray[] = $entryName;
    }
    }

    So, the files of mp3 will be displayed only

    and if you want to display files of doc , or html , or wav, or ram , you should replac mp3 with any of them

    Zeyad

    • User Avatar
      Chad
      Permalink to comment#

      Zeyad, do you know how to reverse this process so I can Hide mp3 files?

  43. User Avatar
    Zeyad
    Permalink to comment#

    But really i want some one to tell me how to limit this display , if the folder havre large quantities of mp3 files
    and want to display 20 files per page when display in browsers

    thanks in advance

  44. User Avatar
    Robert
    Permalink to comment#

    Just came across this. Brilliant. Just what I wanted and as a beginner in php, a nice intro to some basic functionality.
    Thanks.

  45. User Avatar
    Mohammad
    Permalink to comment#

    File size change, bytes to Kbytes!
    Replace:

    print(filesize($dirArray[$index]));

    with:

    print(round(filesize($dirArray[$index]) / 1024, 2));

    ;)

  46. User Avatar
    Commenter
    Permalink to comment#

    Hello, I get this without modifying the code at all:
    Deprecated: Function split() is deprecated in C:\xampp\htdocs\test\.index.php on line 39

    I get a new one of those every time I add a new folder, and when I click on hidden folders I get the same line just a bunch of more times.

    • User Avatar
      Bru
      Permalink to comment#

      Read the comments above. ..split() is replaced with explode() in the latest PHP builds.

  47. User Avatar
    Bru
    Permalink to comment#

    I guess no one is using the “file type” column which didn’t work for me. It seemed to be printing out the full filename rather then the extension so I added the substr function to count -3 back from the end of the filename and then display 3 characters to the right. New code looks like this.

    
             // finds extention of file
             function findexts($filename)
             {
               $filename = strtolower($filename) ;
               $exts = explode("[/\\.]", $filename) ;
               $n = count($exts)-1;
               $exts = $exts[$n];
    	   $exts = substr($exts, -3, 3);	 //added in				 
    	    return $exts;
             }
    

    Hope this helps anyone needing this.

  48. User Avatar
    Qais Patankar
    Permalink to comment#

    Change $exts=split("[/\\.]", $filename);on line 39 to $exts=explode("[/\\.]", $filename);

  49. User Avatar
    Mihai
    Permalink to comment#

    I just uploaded it here
    http://whatshappeningtampa.com/events/

    i created a test directory but when i try to acess that it shows an error
    anything missing from the code ? or i cant have subfolders

    • User Avatar
      Jared
      Permalink to comment#

      I think i’m having the problem you had but from your example it look like you’ve solved it. I can style the first directory, but once you move to another folder, the styles dont stay, but rather they default back to the ugly standard layout. Can you share how to get my subfolders to share the same styling?

  50. User Avatar
    Commenter
    Permalink to comment#

    Hey, I get this when I set:

    $myDirectory=opendir("./folder");

    Every time I add a new file, I get a new set of those 3 errors.

    
    Warning: filesize() [function.filesize]: stat failed for Ny mappe in C:\xampp\htdocs\ny\.index.php on line 76
    
    Warning: filemtime() [function.filemtime]: stat failed for Ny mappe in C:\xampp\htdocs\ny\.index.php on line 79
    
    Warning: filemtime() [function.filemtime]: stat failed for Ny mappe in C:\xampp\htdocs\ny\.index.php on line 80
    
    Warning: filesize() [function.filesize]: stat failed for Ny mappe (2) in C:\xampp\htdocs\ny\.index.php on line 76
    
    Warning: filemtime() [function.filemtime]: stat failed for Ny mappe (2) in C:\xampp\htdocs\ny\.index.php on line 79
    
    Warning: filemtime() [function.filemtime]: stat failed for Ny mappe (2) in C:\xampp\htdocs\ny\.index.php on line 80
    
  51. User Avatar
    Mo
    Permalink to comment#

    Hi!

    this is great. Thank you.

    Is there a way to have the list sorted alphabetically by default? Not it seems to be sorted by modified date. Is this easy to adjust?

    Many thanks!

  52. User Avatar
    Drew Clardy
    Permalink to comment#

    Is there anyway to keep the styling when you enter a folder on the server?

  53. User Avatar
    usman
    Permalink to comment#

    Hi,
    I am using this brilliant code for directory listing with thumbnails using imagemagick for PDF thumbnails.

    the issue is that each time I use the following loop a new jpg file is created. even if it already there..

    Please urgent help required…..

    $path =”images/”;
    $filename = “$path/$namehref.jpg”;

    if (file_exists($filename))
    {
    $tempimg = $filename;
    }
    else
    {
    $result = exec(“convert -density 300 $path/$namehref -thumbnail 150×150 $path/$namehref.jpg”);
    $tempimg = “$path/$namehref.jpg”;
    //$tempimg = “images/preview.jpg”;
    }

    //****using for thumbnail display***/

  54. User Avatar
    jenderalcilik
    Permalink to comment#

    hi, im a total noob about coding. so, excuse my stupid question. where should i put those files? i tried to upload the on the root but nothing is happening.

  55. User Avatar
    yh

    Thanks for the script, it works well. Is there a way to show the same style after clicking on the folders in the same directory as files?

    • User Avatar
      yh
      Permalink to comment#

      to keep the same style when open subdirectories, i managed it work for me:

      in the beginning of this page set a variable to receive a directory

      in the FOR LOOP, i checked the filetype,

      if filetype($namehref) == ‘file’
      print
      if filetype($namehref) == ‘dir’
      link back the same page by using <a href=$PHP_SELF?dir =directory

      you might want to play with the directory to meet your needs.

    • User Avatar
      Jared
      Permalink to comment#

      I’m having issues getting the sub folders to share the same styling. My root folder looks great, but as soon as I click to another folder I get the defaults back again. Could you explain more about how to build the for loop and share an example. Sorry I’m not the best in php.

  56. User Avatar
    Chuck
    Permalink to comment#

    yh would you care to post a copy of your script that you used to maintain the formatting when entering a directory. I’ve tried the example that you posted but I keep getting a parse error.

    Cheers

  57. User Avatar
    Tim
    Permalink to comment#

    A great script.. thank you….it worked first go for me however I have run into an issue that I think relates to the script focusing on file extensions of 3 characters only.
    I ran into an issue where I have .docx and .xlsx files located on the server. While it presents them correctly in the list on the page, when I click to download them the Save window defaults to save them as .zip instead of the original 4 letter extension.

    Are there any changes to the script you can recommend to resolve this?

    thank you in advance

    Tim

    • User Avatar
      Tim
      Permalink to comment#

      oowww just realised I get these results only within IE8 but Chrome seems to work fine.

  58. User Avatar
    Tung

    Hi all,
    I just deployed this script.

    Demo is here http://hopquacuoi.com/kt/

    Anyone can help me to embed this script with
    1. Delete function (can delete/remove displayed file)
    2. Preview function (can preview a file)
    3. Alert function. I want to embed a reminder like this http://www.fremeaujewelers.com/reminder/ into.

    Many thanks
    Tung

    • User Avatar
      Dave
      Permalink to comment#

      Hi Tung
      Any chance of a copy of your updated code for this? Its exactly what I’m after for our internal paper pdf system.

      Thanks

  59. User Avatar
    Sean
    Permalink to comment#

    I’m trying to also password protect this site at manabreakfast.com/commissions and when I add the code to the .htaccess file and upload the .htpasswd file it gives me a 500 error. Is there something else i need to do to password protect this directory and use this styled directory contents?

  60. User Avatar
    George
    Permalink to comment#

    Hello there, this is great!

    One issue though….My browser wont show the file or force download. I get a 403 error. Please help! This is amazingg….

  61. User Avatar
    Ben
    Permalink to comment#

    Hy guys,

    Thank you a lot for this work
    I ‘am getting same warning and try a lot of things to fix it
    No solutions
    Please help me if you can
    this is warning :
    Warning:
    filesize() [function.filesize]: stat failed for aigle_005.jpg in C:\wamp\www\Tests\.index.php on line 79

    Warning: filemtime() [function.filemtime]: stat failed for aigle_005.jpg in C:\wamp\www\Tests\.index.php on line 82

    the both functions are not working

    Thank you

  62. User Avatar
    Emmet
    Permalink to comment#

    Hi I was wondering if there is any modification to this script that will force the user to download each file (PDF, JPG etc.) rather than open it in the browser window?

    Thanks, and great script by the way!

  63. User Avatar
    Hellbeast58
    Permalink to comment#

    I just downloaded and extracted all the files individually into my folders that i want to use this in, and i dont see a change, i only see the default index page, is there something i am missing? or did i not change something within the files to make it work that you didnt explain well enough for me, please help, thanks if you reply/e-mail me as well.

    by the way, i only know basic HTML coding, but i run my own webserver from my home.

    • User Avatar
      Jared Honsvick
      Permalink to comment#

      I believe the files you need are hidden files ( files starting with a “.” period. ). Configure your computer to show hidden files and you’ll see the hidden files in the download folder.

  64. User Avatar
    Hellbeast58
    Permalink to comment#

    first, thanks for the reply!
    second, thats not my issue, i use winrar to open the zip, and can see, move, and modify the files, they just wont load in my website, and if it matter im running it with apache 2.2 on ubuntu 12.04 LTS

    • User Avatar
      bud
      Permalink to comment#

      Do you have php enabled and using the correct chmod settings?

  65. User Avatar
    Hellbeast58
    Permalink to comment#

    doubt it if thats something extra you have to change, any way to help me with that to see if thats the issue?

    • User Avatar
      Jared Honsvick
      Permalink to comment#

      Hmmm….Not sure about that one. I loaded the files onto my server and it just worked. Sorry….Good luck.

  66. User Avatar
    Hellbeast58
    Permalink to comment#

    ok so i got php5 installed now, is there anything else i could try “bud”?

  67. User Avatar
    bud
    Permalink to comment#

    Personally,I have no idea how to set php up on a server.But if you have that done test it to make sure it works.Try a couple of easy php scripts and then move on to this one.

  68. User Avatar
    Hellbeast58
    Permalink to comment#

    just so you know if using linux to host the server

    sudo apt-get install apache2
    sudo apt-get install php5
    sudo apt-get install libapache2-mod-php5
    sudo /etc/init.d/apache2 restart

    and i also got it working by point the links on the page to the actual .index.php file, but for some reason it would not point to the file automatically, had to make the link like normal

  69. User Avatar
    Rajesh
    Permalink to comment#

    Using html how to open display directory contents in tomcat server..pls help me

  70. User Avatar
    Chris Lundie
    Permalink to comment#

    I am trying to find out the exact code to replace so I can search for all files with names starting E05 H06.mp4 I would like to Deliver files only that are E05. Any help would be appreciated

  71. User Avatar
    Lance
    Permalink to comment#

    Having the same issue as Jared. Would like to keep the styling within the folders that are listed. Anyway to do that? Yh presented somewhat of a solution but i have no way of implementing that as I am a PHP novice.

    • User Avatar
      Lance
      Permalink to comment#

      Hmm….it could be as easy as putting all of the original folders and files to make this happen in each subdirectory?

    • User Avatar
      Lance
      Permalink to comment#

      Hmm….it could be as easy as putting all of the original folders and files to make this happen in each subdirectory?

      …..nope that is way too time consuming and takes a lot when you have a pretty elaborate directory tree structure.

    • User Avatar
      Lance
      Permalink to comment#

      Alright. I did it the hard way. I copied the .index.php file into the sub folders and changed out the link to the sortable.js and the .css file and it worked like a charm. I’m much more fluent with css and html than I am in php. I’m sure there is a better way to do this….but until then I have to use this.

  72. User Avatar
    josue contreras
    Permalink to comment#

    the script is working in my website, but the icons are not working. can some one be so kind as to give the steps to install this script. I am a bit slow on php. the specific step by step instruction will realy help.

  73. User Avatar
    bud
    Permalink to comment#

    You have to make sure the path to the icon images is correct.I use this script in multiple locations but the images for the icons I use the full location address-no shortcuts so that I can use the script this way

  74. User Avatar
    josue contreras
    Permalink to comment#

    Where do you find the path for the icon images. What i did is this:
    1. I downloaded the zip file
    2. I extract the content
    3. I took the content of the file and put all the content in the file on the server that I want to generate links.
    4.I directed the page to load on:
    http://www.exeple.com/none/.index.php

    It works but the images on the left does not appear.
    I know I am doing something wrong. This is a freat code. If i dont figure it out, it will be ok, i will use it as it is now. but i will never learn if I dont ask, and I just dont want to half way do something. Your help is greatly appricated. thanks

  75. User Avatar
    bud
    Permalink to comment#

    Don’t forget that the directories have a dot in front of them – .images

    If you got rid of that dot in front of the folder them it wont work.I see there are limited icons that come with this script.The css file is where the images are set for the file types.make sure it points to the correct location as I mentioned above

  76. User Avatar
    bud
    Permalink to comment#

    By the way,the page you posted does not show the script you are talking about.There is nothing on that page that I saw was relevent to the script either????????

  77. User Avatar
    josue contreras
    Permalink to comment#

    sorry, but the website was just an exemple is not an active website, sorry for that. I see what you mean about the css file to point to the .images folder. I have not done that. thanks a lot will try it and let you know. thanks again. very helpful.

  78. User Avatar
    Tide
    Permalink to comment#

    Hello
    I wonder if this code allows you to hide files with. Html or. Php in the same directory as the images

    I thank you in advance for help

    • User Avatar
      Chad
      Permalink to comment#

      Tide, I agree. I see people adding code to only show mp3 files or doc files. I would love to reverse that so we DON’T show php files.

  79. User Avatar
    Raph
    Permalink to comment#

    Thanks mate! I have removed the “Show Hidden Files” function for security reasons.

  80. User Avatar
    DebbyP
    Permalink to comment#

    Ralph, how did you modify to remove the “Show Hidden Files”?

    • User Avatar
      DebbyP
      Permalink to comment#

      I tried the solution above (Benjamin September 29, 2010) and got all the individual files, no folders (not what I want) and when I clicked on the show hidden files they were all there so that didn’t work for me.

    • User Avatar
      Sixxkilur

      I tried to use Markdown to place code blocks but it would parse my html and PHP code that was in the code blocks. I am unable to place the code at all in this form ” this forum should stick with bb code no one is going to spend over an hour to learn how to properly use markup and whatever else this forum is using for replies to reply with a few words.” That being said

      I commented out the php echo string on the last echo of .index.php
      after ?php

      
      ?php //echo("$atext hidden files"); ?>
      
  81. User Avatar
    DebbyP
    Permalink to comment#

    Anyway to make it work in all directories and sub directories without having to copy the code into each directory?

  82. User Avatar
    DebbyP
    Permalink to comment#

    Looking to make it work somewhat like this ftp://triad-atlanta.com/

  83. User Avatar
    Kelum

    this is awesome , want to know how to give “delete” function to each of these files

  84. User Avatar
    Lisa

    Finding this made my day!!! thank you soo much. I am having 1 problem if anyone knows. I added the code

    // Set Forbidden Files
    $forbiddenExts = array("php", "ico", "html", "LCK", "js");
    
    // Gets Each Entry
    while($entryName = readdir($myDirectory)) { 
    $exts = explode(".", $entryName); 
      if(!in_array($exts[1],$forbiddenExts)) { 
        $dirArray[] = $entryName;
      }
    }
    

    I password protected the directory so each file has a “LCK” file. When i added that extension to the “$forbiddenExts” line but they still show up. If I add “pdf” to the code then the pdf files and the pdf.LCK file are hidden. I only want to hide the LCK file. Any ideas?

    I did add “IndexIgnore *.LCK” to my .htaccess file but now that i am using this they show up again. please help!

  85. User Avatar
    Hans
    Permalink to comment#

    I’m using this code to create the directory and opening the index.php page in an iFrame so I can show different directories via the menu bar. The problem I am having is that the selected documents are opening within the iFrame when I need them to open in a new window. I’ve added target=’_blank’ to the output table but it’s not working. Any advice?

    • User Avatar
      Hans
      Permalink to comment#

      Please ignore my question. I’ve been staring at this too long and my iFrame was referencing a different file! Rookie mistake! target=’_blank’ works exactly like it should.

    • User Avatar
      Ken
      Permalink to comment#

      I can’t seem to get the returned links to open in a new window or tab.

      Adding the target=’_blank’ causes an error that not any of the files load

      Any help?

  86. User Avatar
    Amit Bhardwaj
    Permalink to comment#

    Hi,
    First of all thanks for the wonderful script it helped me a lot.
    The script is working perfectly, the issue I am facing are
    1) I have a big list of files on my server, I want that if a search could be integrated to this script. That would really help me.
    2) If its possible to show alphabets at the top so that when some1 clicks them, only files starting with that alphabet will be shown.

  87. User Avatar
    Saf
    Permalink to comment#

    Hi,

    This has been an invaluable post however I, like a few others here, am looking for a way for this style of display to extend to subfolders. Placing the files in every subfolder is extremely impractical for my use.

    If anyone is aware of how to do this, please let me know!

  88. User Avatar
    John
    Permalink to comment#

    How do I keep from loosing the formatting when I go into a subdirectory?

    Thanks for the post,
    John

  89. User Avatar
    Diego
    Permalink to comment#

    This is brilliant!!

    I am currently using it and we are loving it :)

    Thanks!!!

  90. User Avatar
    mark
    Permalink to comment#

    Hi, Thanks for this post. It worked for me! But I would appreciate if it included a “delete” button in which i can delete uploaded files.

  91. User Avatar
    Bryan
    Permalink to comment#

    I have the following error’s when running the code. Can somebody help me figure out what part of the code needs to be changed. I get this error and other just like it for file size. Thanks

    Warning: filemtime() [function.filemtime]: stat failed for Combs 2012 Bell TNG.pdf in /home2/combsb/public_html/file_display.php on line 80

  92. User Avatar
    Eirik
    Permalink to comment#

    Nice piece of code. However I would like to display the time properly. HH:MM DDMMYY . Not too familiar with code like this, so could anyone point me to the place where the date and time is being displayed so I can correct it?

  93. User Avatar
    Cory
    Permalink to comment#

    Thanks alot! This really helped me out!!

  94. User Avatar
    Wilds
    Permalink to comment#

    Removed show hidden file for securuty

    Handle subdirectories (now subfolder keep the same style)

    http://pastebin.com/edvpqBg5

    ps: Sorry, i’ve translate text in italian

  95. User Avatar
    Paul
    Permalink to comment#

    I’ve done an update to the version of the script that wilds released. There were some bugs in his code that made the date and size not appear properly. I’ve also changed and added a few things. You should only have to place this in the root now and all the styles will be applied to sub-folders. The code has been separated from .index.php into a seperate file .engine.php. I also changed and added more icons and file types. There is a header.html and footer.html so you can customize without altering the file associated with the listing.

    That’s about it. You can find a demo of it on my site(ish) (it’s not up all the time).

    Demo
    http://squirrelhouse.no-ip.info/

    Here is the download
    http://squirrelhouse.no-ip.info/Downloads/PHP/DirList.7z

    You’ll need 7-zip for the file

  96. User Avatar
    Hans
    Permalink to comment#

    Thank you all who have provided examples and tweaks to this code. It’s incredibly helpful.

    Is it possible to add a column to the left of each document name that contains a red X that will allow only an admin to delete the file? This red x would only appear when the user is logged in as the site admin.

    Is it also possible to add a file uploader that is only visible to the site admin that will place the file in the folder being viewed?

    Right now I’m using the script to display the directory content and have the site admin use FileZilla to manage the documents. It would be so much easier to just manage everything through the website.

  97. User Avatar
    Paul
    Permalink to comment#

    I discovered a security issue in the version that Wilds submitted (which is what I based mine off of). I’ve corrected the problem and updated both the original DirList.7z and DirList2.7z. For the people who already downloaded my version, you need to either download again or add this code at the beginning of the list_files function in engine.php:

    Delete the if statement where it checks $_SERVER[‘QUERY_STRING’] || …
    And replace it with this:

        if(!isset($_SERVER['QUERY_STRING']))
            $currdir = ".";
        else
            $currdir = $_SERVER['QUERY_STRING'];
    
        $currdir = str_replace("..", "", $currdir);
        $currdir = str_replace("/.", "", $currdir);
        $currdir = str_replace("./", "", $currdir);
        $currdir = str_replace(":", "", $currdir);
    
        if(substr($currdir, 0, 1) == "/" || $currdir == "")
            $currdir = ".";
    

    Before if the user typed .. or ./ or any other variation, they would be able to view directory listings outside of the server root directory (not read or modify). It looks like Wilds already thought of that, but the code was not working right.

    http://squirrelhouse.no-ip.info/Downloads/PHP/DirList.7z

    • User Avatar
      RB
      Permalink to comment#

      Paul, I too, would like to see your handi-work (DirList7z. & DirList2.7z) utilizing Wilds killer script with ext. header/footer html includes. It appears that squirrellhouse URL has taken a nap… thanks in advance!

  98. User Avatar
    Kole
    Permalink to comment#

    Thanks for all your help! i want to implement Paul’s DirList.7z solution, but I can’t download it, the link is OK…
    Can someone else send the same script?

    Thanks,

  99. User Avatar
    GIOhnny
    Permalink to comment#

    I’ve manage to add a delete.png image at the end of each row. Nothing difficult here, but I don’t know how to delete the file when I press the image.
    Any suggestions from someone who knows, please ?

  100. User Avatar
    Joze
    Permalink to comment#

    @Paul – I also tried your download link – (http://squirrelhouse.no-ip.info/Downloads/PHP/DirList.7z), but failed to download. Could you possible upload to a dropbox etc. Thanks in advance.

  101. User Avatar
    mark
    Permalink to comment#

    I noticed that whenever I try to upload a file with more than 2mb filesize. An error occurs. The file failed to be uploaded.

  102. User Avatar
    Colin
    Permalink to comment#

    Thanks – this is very cool!

    Related question – is there any way to get (relatively) the same effects without using PHP (or any other server-side scripting)? I recognize the depth of what I’m asking – I’d like to apply a style to an open directory that gets regularly burned to a CD for distribution, without having to keep updating the coding each time the directory contents change.

    The files in the directory get updated on a random schedule. I want the end user to see the directory of files, but without it looking like my kids made it.

  103. User Avatar
    Dan
    Permalink to comment#

    I love this script.
    Except I am finding some flaws in it and I was wondering if someone could please fill in the missing pieces.
    The main script is beautiful, but I want to go to a specific directory.

    The second script provided by Wilds, which is in italian, works great for displaying another directory in the proper CSS style, but the filesize and date modified does not work properly.

    Also for some reason when I change directories, I cannot display or download the file because when I click on it, it wants to give me a directory structure that is different then my directory path.

    So if anyone can help, I would be so very happy.

  104. User Avatar
    Wilds
    Permalink to comment#

    Fixed filesize and date bug: http://pastebin.com/edvpqBg5
    Sorry, but I can’t replicate the problem with directory structure.

    • User Avatar
      Luis
      Permalink to comment#

      Hi Wilds, I have some errors with ur script. I’m using it in a site with a lot of files but the issue is that I can’t download files with .exe .jpg or .txt extensions, works fine with rar or zip files. Could you check this please. Thanks.

    • User Avatar
      Luis
      Permalink to comment#

      Nevermind, is working fine. my server was the problem. thanks.

      BTW. there’s a way that instead of displaying “directory contents” (contenuto) it shows the name of the current directory ??

    • User Avatar
      wawan
      Permalink to comment#

      Hello, I’m using ur code. I have a problem here, if a folder has character like: ” ,+’ etc it won’t display the files inside it, so I should rename/remove the character. how to fix this?

    • User Avatar
      Dave
      Permalink to comment#

      Hi. I understand files can be hidden ie (.) before the filename but I have a file in the same directory which I cannot use the (.) before. Is there any code to add which I can specify to hide a file regardless of whether it has a (.) infront or not?

      Thanks

  105. User Avatar
    Wilds
    Permalink to comment#

    Ok, now it shows the curren directory name: http://pastebin.com/SjbjbqPR

  106. User Avatar
    thaison
    Permalink to comment#

    I love this script.
    But can I show Dictionary (sort A->Z), then file (sort A-> Z)

  107. User Avatar
    Hans
    Permalink to comment#

    Has anyone figured out a way to allow for certain users to delete files? Can I add this script to a page with restricted access so they can delete old files. I’m trying to build a site that allows different chefs to upload their menus as they change. I’ve created the members login section and figured out a way for each chef to upload PDFs. I would like for them to be able to delete older menus from their individual directories. This delete function would be restricted to each chef so they can only delete their own files

  108. User Avatar
    Hans
    Permalink to comment#

    I can’t get this to work on any Android devices. It works perfectly in all recent browsers and Apple products but not on any of the Samsung phones I have tested. Anyone else have the same issue?

  109. User Avatar
    adarsh
    Permalink to comment#

    superb code but to display the same styles in sub directories i have to place all the files into other sub directories as well ;-)

  110. User Avatar
    Bud
    Permalink to comment#

    I got this working sometime ago but have returned because I am looking to see if anyone have ammend or added the code to display an images demensions in the list of files

  111. User Avatar
    Bud
    Permalink to comment#

    Okay,I found this snippet on this ” php snippet” section.

    <start>
            <?php
    
          list($width, $height, $type, $attr) = getimagesize("url/to/image.jpg");
    
          echo "Image width " . $width;
          echo "Image height " . $height;
          echo "Image type " . $type;
          echo "Attribute " . $attr;
    
        ?>
    

    How can this be added to the styled directory contents script .I am a complete novice and have no idea where to add it?

    Any help would be greatly appreciated

  112. User Avatar
    Bud
    Permalink to comment#

    I got it working on my own-

    First time I was able to do something like this on my own with php

    cool……..

  113. User Avatar
    Bryan Cady
    Permalink to comment#

    I have a directory with several subfolders. The parent is username and password protected with the plesk panel app. When I put this code in the parent directory, it seems to conflict with the login credentials and gives me a 404 error for the page. If I put in my old directory indexing code in the parent directory, it looks pretty ugly but when I click on the subfolders, those work as this post states since I have this post’s files in each directory.

    Does anyone have any tips and fixing the login conflict in the parent?

    Thanks
    Bryan

    • User Avatar
      Bryan Cady
      Permalink to comment#

      Nevermind. I went ahead and just coded up an html page for the parent folder and that solved my issue. Thanks though

  114. User Avatar
    Dave
    Permalink to comment#

    Hi. After downloading the files, where is the best place to put the .images folder?

  115. User Avatar
    Dave
    Permalink to comment#

    Sorry, just to add to my last post. When I load the browswer I get “Translate” from Spanish.. Is there an english version or can I edit the scriprt.

    Thanks

  116. User Avatar
    Preston
    Permalink to comment#

    I need to modified this code to prevent the showing of XML and MHT files

    Also, want to sort by date.

  117. User Avatar
    DoctorDavid
    Permalink to comment#

    Love the script, but need to change directorys. I’ve tried this
    // $myDirectory=opendir(“.”);
    $myDirectory=opendir(“/var/www”);
    but only get the style display page with out any results. Is there a simple was to
    switch the directory from “.”

    • User Avatar
      DoctorDavid
      Permalink to comment#

      I guess it’s always good to answer your own question post.

      $path = “/home/david/Downloads”;
      // Opens directory
      // $myDirectory=opendir(“.”);
      $myDirectory=opendir($path);
      Any directory path that is placed in $path = ” “. Will now be displayed

  118. User Avatar
    Preston
    Permalink to comment#

    Trying to exclude certain file extensions. When I use Benjamin’s code above, I get a bunch of unknowns instead of file names.

    If I use zeyad’s code above, I get a page without any files. No matter what extension I put in it doesn’t show any files.

    Help please…

  119. User Avatar
    Preston
    Permalink to comment#

    I have the exclude file extensions working but…I lose the formatting when I go into sub directories

    Can someone tell me exactly what controls that in the code?

  120. User Avatar
    Bryan
    Permalink to comment#

    I had to put the files in each sub-directory to get it to work right.

  121. User Avatar
    Preston
    Permalink to comment#

    Ok, I lied. Here are my issues:

    Cannot filter out file extension that I do not want
    Would like to sort by date
    The icons do not show next to the file name.

  122. User Avatar
    cody

    i would liketo create a link to show the parent folder… but not allow to show hidden files.. like the.htaccess .index.php…..

    • User Avatar
      Plotz
      Permalink to comment#

      Is this question already solved?
      I also want to show the parent folder, but NOT hidden files and NOT hidden switch.

      Thx

  123. User Avatar
    bud

    Cody,make sure the path to the images used in the file is correct.I had to fix that when I did this too.

  124. User Avatar
    Luis

    How to replace spaces for %20 in directories that have spaces in name ?
    E.g: “www.mysite.com/?index/my images”
    I want it like this “www.mysite.com/?index/my%20images”

  125. User Avatar
    Seshu
    Permalink to comment#

    Thanks, it worked for me.. with out any changes

  126. User Avatar
    Kaydev
    Permalink to comment#

    File images are only working in my root directory. What file and line(s) of code do I need to edit to get the file images to show up in sub-directories as well?

  127. User Avatar
    Kaydev
    Permalink to comment#

    Answered my own question!

    Turns out sub-folder icons are working. My site mainly has PDF files. The code has no PDF icon code in the css. I just needed to add the code lines for PDF files!

    SOLVED!

  128. User Avatar
    Scott
    Permalink to comment#

    I am wanting to use this for a video library, so I have $myDirectory=opendir(“Videos”); instead of $myDirectory=opendir(“.”);.

    However, when I click on the link to the file I get a 404 error, and when I look at the 404 error page I notice that it says the requested URL is http://localhost/“name of video” instead of http://localhost/Videos/“name of video”

    How can I correct that?

  129. User Avatar
    bill
    Permalink to comment#

    Is there a way to show the list without showing the parent folders? “.” and “..”?

    • User Avatar
      Simone
      Permalink to comment#

      If you remove || ($currdir != '.' &amp;&amp; $dirArray[$index] == "..") from if (substr("$dirArray[$index]", 0, 1) != $hide || ($currdir != '.' &amp;&amp; $dirArray[$index] == "..")) {
      It should remove the parent folders.

      That’s what worked for me anyway.

  130. User Avatar
    harsh
    Permalink to comment#

    how to rename the directory files name ??plzzz help me

  131. User Avatar
    Marcus Rerre
    Permalink to comment#

    has no way to sort by date, by default?

  132. User Avatar
    Peter
    Permalink to comment#

    Hi

    I am trying to use this code multiple times on the same webpage and I get wierd results.
    The first time it displays the files from the folder correctly.
    The second time it displays both the files from this folder and the first folder.
    Then third time you get the files from all 3 folders.
    How can I stop the files being repeated?
    Thanks

  133. User Avatar
    Tim
    Permalink to comment#

    Everything works beautifully in Chrome however IE8 does not display any icons.

    Is there anything I can modify to make it more compatible with IE8? Unfortunately I’m forced to support this browser.

    Thanks and awesome job!

  134. User Avatar
    Tom
    Permalink to comment#

    This is awesome!

    just one error I’m seeing, if your filename has an apostrophe in it the file icon will default to the document icon.

    For example, an audio file named: John’s Song.mp3 will not show the audio icon because of the apostrophe.

    Any idea how to fix this?

  135. User Avatar
    pedro
    Permalink to comment#

    Does anyone know how to trim the names of folders and files, for example only show the first 25 characters of the filename.

    Thanks in advance

  136. User Avatar
    Kim
    Permalink to comment#

    Is it possible to show different folder icons for directories?
    For example I would like a different icon for my photos directory, my video directory my zip directory etc..
    Many thanks for any help, Kim.

  137. User Avatar
    Caryn
    Permalink to comment#

    How do we sort the files by last modified date (by default). I would like the files to be sorted by date when the page is opened. Thanks.

  138. User Avatar
    Liuky
    Permalink to comment#

    hi
    how to implement a style for all subfolders in the file?
    thank you

  139. User Avatar
    LuckyMe

    Thanks for this great script. :)

    I’ve got a minor problem. I used the modified version from Wilds. Filesize only shows the word “bytes” and last modified only displays “Jan 1 1970 1:00 AM” on all files. How can I solve this?

  140. User Avatar
    lukky

    for warning : Warning: filesize() [function.filesize]: stat failed for….

    try this : $dirArray[$index]=$_SERVER[“DOCUMENT_ROOT”].”/dash/welcome/gbr_email/”.$dirArray[$index];

  141. User Avatar
    lukky

    for warning : Warning: filesize() [function.filesize]: stat failed for….

    try this : $dirArray[$index]=$_SERVER[“DOCUMENT_ROOT”].”/YOUR FOLDER/”.$dirArray[$index];

  142. User Avatar
    Fabrizio
    Permalink to comment#

    I recive this error when try to click on my document folder :

    Forbidden

    You don’t have permission to access /personale/vedi/APPO/ on this server.

    Additionally, a 404 Not Found error was encountered while trying to use an ErrorDocument to handle the request.

    any idea?
    Thanks Fabrizio

  143. User Avatar
    John
    Permalink to comment#

    Hi, I really like the code and the modification that wolf did to it, But id like to know if anyone has been able to include javascript to create a button or slider that switches between list and grid view. And how can i change the default folder without getting errors.

    • User Avatar
      John
      Permalink to comment#

      By default folder, I mean i have the page as index but i’d like to display a different directory in my index page.

  144. User Avatar
    Ben
    Permalink to comment#

    Hi, i have it all working lovely for local files but i would like to connect to a network folder that uses sftp. How easy is this to do as im new to PHP and a copy & paste job would be great.

  145. User Avatar
    Alex
    Permalink to comment#

    Hello,
    I am using this script for watching video’s from my website. But when I use target=”_blanc” it also opens the ‘previous directory’ in a new tab. Is there any way to only open files in a new tab?

    Thanks in advance.
    Regards, Alex

  146. User Avatar
    zac2613
    Permalink to comment#

    @pedro

    Quote
    Does anyone know how to trim the names of folders and files, for example only show the first 25 characters of the filename.

    Find
    // Gets favicon.ico, and displays it, only if it exists.
    Add Above
    // Trim the filename titles to 25 chars
    $name = strlen($name) > 25 ? substr($name, 0, 25) . ‘…’ : $name;

    You can alter the amount to show by changing the 25 x2 above to suite your needs.

  147. User Avatar
    Campbell
    Permalink to comment#

    I have a website built using html5 not php, but would like the same type of styling on directories.

    Is that possible?

    cheers

  148. User Avatar
    Garry Lawton
    Permalink to comment#

    Neat Code works like a charm . to stop it giving the option of diplaying the hidden files I just removed the line of code that does that.

    What I am wondering is how could you make it so it only shows the file names and make the text larger if it is being viewed on a cell phone or make it responsive to the size of the screen ( without the file “Type” , ” Size” and “Date Modified “

  149. User Avatar
    Private Here
    Permalink to comment#

    Thanks a lot.

  150. User Avatar
    Spipmalion
    Permalink to comment#

    Added background-size: 16px 16px; in order to avoid a display bug with favicon images bigger than this size, also checking some folders to find the favicon :

    $chemins_favicon = array(
    “img/”,
    “images/”,
    “”
    );

                foreach($chemins_favicon as $c) {
                    $favOK = $namehref."/".$c."favicon.ico";
                    if(file_exists($favOK))
                    {
                        $favicon=" style='background-image:url($favOK);background-size: 16px 16px;'";
                        $extn="&lt;Website&gt;";
                    }   
                }
    
  151. User Avatar
    John
    Permalink to comment#

    Hello,
    I’d like to know if and how i can add a script to a selected item in the list, Perhaps a script to send the file through email or delete it. Any help would be appreciated. Please comment if you do not understand.

  152. User Avatar
    JohnM
    Permalink to comment#

    Very cool script. PHP is all very new to me but thanks to all the comments and suggestions I was able to get the script up working the way that I wanted.
    A change I made was to the box size, I didn’t want it exploding across the screen. You can control this in the .styles.css under the tag #container.

    #container {
    width: 800px;
    margin-left:auto;
    margin-right:auto;
    box-shadow: 0 15px 10px -5px rgba(0,0,0,0.5);
    position: relative;
    background: #dbe7f6;
    }
    You can add width, margin-left, and margin-right parameters to define the box the way you would to see it on the screen.

  153. User Avatar
    Matrix
    Permalink to comment#

    Hi, nice script, it’s working perfect! I need to open directories in new tab or new window. How can I do this? I don’t know PHP :(

    Best regards!

  154. User Avatar
    Guilherme
    Permalink to comment#

    Hello!

    I’m not a developer, but Im trying to follow the steps to make the demo files work for me. What I did was just copy the hidden files to the folder I’m trying to list files, but nothing happened. I tried to access it as local machine and maybe this is the problem. What I need to do is to embed the list of files in my website. For that, I’m using iframe to make it happen. It worked with google drive, but is not working in local machine. Any ideas? Thanks!

  155. User Avatar
    Jorge Jimenez
    Permalink to comment#

    Greetings.

    I used the code and is working like a charm. but when i view the files and click them it doesn’t start downloading, i noticed the file path is not the real one when i click them, only work if i “right click and save as”.

    Is there a way to solve this?

    Thanks in advance.

  156. User Avatar
    Saad
    Permalink to comment#

    Please can someone tell how can I put an add unit within the listing… say like after 5 folders or files I have and adsense unit…

  157. User Avatar
    Syreeta Albin

    Nice discussion – Incidentally , people require a NY DTF ST-330 , my business partner filled out and faxed a template version http://goo.gl/Cw08AX

  158. User Avatar
    Alex
    Permalink to comment#

    Thanks for amazing script, it worked without problem however I was wondering if it is possible to make this recursive to list even subfolder content without uploading the files on all folders plus breadcrumb.

  159. User Avatar
    deadlly
    Permalink to comment#

    replace line 33 with this :
    $return.= ‘DROP TABLE IF EXISTS ‘.$table.’;’;

  160. User Avatar
    dec0der
    Permalink to comment#

    How to display each of the files MD5 or SHA?

  161. User Avatar
    Tosan
    Permalink to comment#

    Great people please i want to embed a pdf viewer in my php application, i added the code from the get file names section of the php code i got from this site its not displaying he documents
    // Gets File Names
    //
    $name=$dirArray[$index];
    $namehref=’/achs0/ViewerJS/PDF_findfont(p, example.local.css, encoding, embed).pdf/($dirArray)'[$index];

  162. User Avatar
    Rick Altman
    Permalink to comment#

    This is a wonderful solution to a dilemma that has plagued me for quite some time; I’m grateful! I am displaying this within a mobile app, where there is no built-in navigation. Is there any way to add a “go up one level” button?

    The page in question is at http://www.presum16.com/seminars.

  163. User Avatar
    Renato
    Permalink to comment#

    Hi! Is there any way to protect wit password?
    Thanks

  164. User Avatar
    paul
    Permalink to comment#

    Hi,
    Great script !
    PDF files do not show with an icon, so …
    I have added an image “pdf.png” (16×16) into .images
    and added into :
    .style.css

    table tr td:first-of-type a[href$=”.pdf”],
    {background-image: url(./.images/pdf.png)}

    But it does not work,
    please can you correct me ?
    Thanks ;)

  165. User Avatar
    Ricardo
    Permalink to comment#

    Hey everyone,
    Im loving this code

    Anyone knows how to keep the “current directory” and “Parent Directory” shown at all times?

    Thank you very much, hope to get answers!

  166. User Avatar
    Richard
    Permalink to comment#

    This is GREAT!!!

    I just have one question, how do I hide folders from displaying on the list?

Submit a Comment

Posting Code

You may write comments in Markdown. This makes code easy to post, as you can write inline code like `<div>this</div>` or multiline blocks of code in triple backtick fences (```) with double new lines before and after.

Code of Conduct

Absolutely anyone is welcome to submit a comment here. But not all comments will be posted. Think of it like writing a letter to the editor. All submitted comments will be read, but not all published. Published comments will be on-topic, helpful, and further the discussion or debate.

Want to tell us something privately?

Feel free to use our contact form. That's a great place to let us know about typos or anything off-topic.

icon-closeicon-emailicon-linkicon-logo-staricon-menuicon-searchicon-staricon-tag