Directory Contents

PHP: Directory Listing

A common request is to be able to produce a list of some or all of the files in a directory — similar to the default index page provided by most web servers, but with more control over the content and formatting.

Another goal might be to take some action on the files using PHP. In either case the first step is to query the file system to return a list of directories and files.

The functions presented below provide the means to extract the file names and other properties from a single directory, or to explore subdirectories recursively.

PHP 5 introduces the scandir function which will «List files and directories inside the specified path» but won’t recurse or provide additional information about the listed files.

If you are using PHP 5 or higher check out our new article on Directory Listing using SPL classes for a much neater approach, and our new FileList PHP class.

Single Directory Listing

To get started, here is a simple function that returns a list of files, directories and their properties from a single directory (more advanced versions of this function can be found further down the page):

You can use this function as follows:

The variable $_SERVER['DOCUMENT_ROOT'] should resolve to the root directory of your website. e.g. /var/www/public_html

The return value is an associative array of files including the filepath, type, size and last modified date, except when a file is actually a directory, in that case the string «(dir)» appears instead of the filesize. The filenames take the same stem as the function call:

«,print_r($dirlist),»«; /* sample output Array ( [0] => Array ( [name] => images/background0.jpg [type] => image/jpeg [size] => 86920 [lastmod] => 1077461701 ) [1] => . ) */ ?>

«,print_r($dirlist),»«; /* sample output Array ( [0] => Array ( [name] => ./ images/background0.jpg [type] => image/jpeg [size] => 86920 [lastmod] => 1077461701 ) [1] => . ) */ ?>

If you want the output sorted by one or more fields, you should read the article on Sorting Arrays of Arrays or try out one of our DHTML Sorting Algorithms using JavaScript.

We also have an article on Directory Listing using SPL classes (DirectoryIterator and SplFileInfo) which introduces many new options for filtering and sorting the output.

Displaying File List in HTML

To output the results to an HTML page we just loop through the returned array:

// output file list in HTML TABLE format echo «

\n»; echo « \n»; echo «

\n»; echo «

\n»; echo «

\n»; foreach($dirlist as $file) < echo " \n»; echo »

\n»; echo «

\n»; > echo «

\n»; echo «

Name Type Size Last Modified
\n»; echo » \n»; echo » \n»; echo « «,date(‘r’, $file[‘lastmod’]),»

\n\n»; ?>

This code can be easily modified to: make the output a list instead of a table; make the file names actual links; replace the names with icons based on file type or extension; etc.

Display PNG images in a TABLE:

For example, to display only PNG files, just add a condition to the output loop:

// output file list as HTML table echo «

\n»; echo « \n»; echo »

\n»; echo «

\n»; echo «

\n»; foreach($dirlist as $file) < if(!preg_match("/\.png$/", $file['name'])) < continue; >echo « \n»; echo «

\n»; echo »

\n»; echo «

\n»; > echo «

\n»; echo «

&lt/th> Name Type Size Last Modified
\» width=\»64\» alt=\»\»> \n»; echo » \n»; echo » \n»; echo « «,date(‘r’, $file[‘lastmod’]),»

\n\n»; ?>

Here you can view the complete source code for this example.

This will have the effect of skipping all files whose name does not end with .png. You could also apply conditions based on the file type, size, or last modified timestamp.

One last example, listing only PDF files and having the file name link to the file:

// output file list as table rows foreach($dirlist as $file) < if($file['type'] != 'application/pdf') < continue; >echo « \n»; echo »

\n»; echo »

\n»; echo «

\n»; > ?>

Name Type Size Last Modified
\»>»,basename($file[‘name’]),» \n»; echo » \n»; echo « «,date(‘r’, $file[‘lastmod’]),»

Here you can view the complete source code for this example.

If you want to display, for example, a thumbnail as a link to a larger image, or even a video, just give the two files the same name and in the script above use str_replace or similar function to modify either the link href or the link contents. See our article on listing images for examples.

Using the SPL DirectoryIterator and FilterIterator classes we can now specify a pattern to match when accessing the file list so only matching files are returned. More on that here.

Recursive Directory Listing

Now that we’ve got this far, it’s only a minor change to extend the function in order to recursively list subdirectories. By adding a second parameter to the function we also retain the previous functionality of listing a single directory.

To make use of the new functionality, you need to pass a value of TRUE (or 1) as the second parameter.

Before recursing the script first checks whether sub-directories are readable, and otherwise moves on to the next item so as to avoid permission errors.

As before, the return value is an array of associative arrays. In fact the only change is that you have the additional option of a recursive listing.

Limited Depth Recursion

This final example adds another feature — the ability to specify how deep you want the recursion to go. The previous code would continue to explore directories until it ran out of places to go. With this script you can tell it to not go deeper than a fixed number of levels in the file system.

As before we’ve added a single new parameter and a few lines of code. The default value of the depth parameter, if not defined in the function call, is set to FALSE. This ensures that all previous features remain and that any legacy code won’t break when the function is changed.

In other words, we can now call the getFileList function with one, two or three parameters:

This is a good example of how a function can evolve over time without becoming unmanageable. Too often you see functions that were once useful become unusable because of parameter bloat.

Fileinfo replaces mime_content_type

The mime_content_type function has been deprecated in recent version of PHP and replaced with the PECL Fileinfo extension was never actually deprecated, despite announcements to the contrary.

If you are seeing errors in your program due to this, the following patch should work:

This is the same function as seen at the top of the page, just with a check for the mime_content_type function inserted at the top to determine which method we use to get the file type.

If you are scanning a complex directory system you probably want to declare $finfo as a global variable to avoid having to re-instantiate it when the function recurses.

References

Источник

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: 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).

   

Directory Contents

// 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") else 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="<Directory>"; $size="<Directory>"; $class="dir"; >else < $class="file"; >// Cleans up . and .. directories if($name==".") if($name=="..") // Print 'em print(" "); > > ?>
Filename Type Size (bytes) Date Modified
$name $extn $size $modtime

$atext hidden files"); ?>

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); >

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.

Источник

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Make an plain html page containing a directory listing

License

mafintosh/directory-index-html

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

Make an plain html page containing a directory listing. Similar in look and feel to NGINX’s listing page.

npm install directory-index-html 
var toHTML = require('directory-index-html') var entries = [ name: 'test', size: 24424, mtime: new Date() >,  name: 'a-dir/', mtime: new Date() >] console.log(toHTML('/foo/bar', entries))

var html = toHTML(dir, entries)

Render a directory name and listing to an plain HTML string.

dir should be a string containing the directory name.

entries should be an array of entries that are similar to this

 name: 'name-of-file-or-dir', size: 42424, // size in bytes mtime: new Date() // when was this modified >

To figure out if an entry is a directory the module will one of the following things:

  • Check if the path ends with a /
  • See if entry.type === ‘directory’
  • See if entry.mode specifies a directory

There is a small demo server bundled in the repo that serves a directory listing of your current working directory.

To try it out, run node demo.js and visit http://localhost:8080 .

It should show something like this:

Источник

Читайте также:  How to open link in new tab html
Оцените статью