- PHP: Directory Listing
- Single Directory Listing
- Displaying File List in HTML
- Display PNG images in a TABLE:
- List PDF files with links:
- Recursive Directory Listing
- Limited Depth Recursion
- Fileinfo replaces mime_content_type
- References
- Related Articles — Directory Listing
- filetype
- Ошибки
- Примеры
- Примечания
- Смотрите также
- User Contributed Notes 6 notes
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 «
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 «
</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.
List PDF files with links:
One last example, listing only PDF files and having the file name link to the file:
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
Related Articles — Directory Listing
filetype
Возвращает тип файла. Возможными значениями являются fifo, char, dir, block, link, file, socket и unknown.
Возвращает false в случае возникновения ошибки. filetype() также вызовет ошибку уровня E_NOTICE , если системный вызов stat завершится ошибкой или тип файла неизвестен.
Ошибки
В случае неудачного завершения работы генерируется ошибка уровня E_WARNING .
Примеры
Пример #1 Пример использования функции filetype()
echo filetype ( ‘/etc/passwd’ );
echo «\n» ;
echo filetype ( ‘/etc/’ );
?>
Результат выполнения данного примера:
Примечания
Замечание: Результаты этой функции кешируются. Более подробную информацию смотрите в разделе clearstatcache() .
Начиная с PHP 5.0.0, эта функция также может быть использована с некоторыми обёртками url. Список обёрток, поддерживаемых семейством функций stat() , смотрите в разделе Поддерживаемые протоколы и обёртки.
Смотрите также
- is_dir() — Определяет, является ли имя файла директорией
- is_file() — Определяет, является ли файл обычным файлом
- is_link() — Определяет, является ли файл символической ссылкой
- file_exists() — Проверяет существование указанного файла или каталога
- mime_content_type() — Определяет MIME-тип содержимого файла
- pathinfo() — Возвращает информацию о пути к файлу
- stat() — Возвращает информацию о файле
User Contributed Notes 6 notes
There are 7 values that can be returned. Here is a list of them and what each one means
block: block special device
char: character special device
unknown: unknown file type
filetype() does not work for files >=2GB on x86 Linux. You can use stat as a workarround:
Note that stat returns diffenerent strings («regular file»,»directory». )
I use the CLI version of PHP on Windows Vista. Here’s how to determine if a file is marked «hidden» by NTFS:
function is_hidden_file ( $fn )
$attr = trim ( exec ( ‘FOR %A IN («‘ . $fn . ‘») DO @ECHO %~aA’ ));
if( $attr [ 3 ] === ‘h’ )
return true ;
This should work on any Windows OS that provides DOS shell commands.
Putting @ in front of the filetype() function does not prevent it from raising a warning (Lstat failed), if E_WARNING is enabled on your error_reporting.
The most common cause of filetype() raising this warning and not showing a filetype() in the output (it actually returns NULL) is, if you happened to pass just the ‘Dir or File Name’ and not the complete «Absolute or Relative Path» to that ‘file or Dir’. It may still read that file and return its filetype as «file» but for Dir’s it shows warning and outputs NULL.
eg:
$pathToFile = ‘/var/www’;
$file = ‘test.php’;
$dir = ‘somedir’;
Output for filetype($file) will be returned as ‘file’ and possibly without any warning, but for filetype($dir), it will return NULL with the warning «Lstat failed», unless you pass a complete path to that dir, i.e. filetype($pathToFile.’/’.$dir).
This happened to me and found this solution after a lot of trial and error. Thought, it might help someone.
Note there is a bug when using filetype with for example Japanese filenames :
https://bugs.php.net/bug.php?id=64699
The whole PHP interpreter comes crashing down without anyway to avoid it or capture an exception.
echo «Zum testen müssen tatsächlich existente Namen verwendet werden.
» ;
echo «Pfad und Dateiname müssen getrennt eingetragen und durch einen Punkt verbunden sein.
» ;
echo «Example: [filetype(\»../dir/u_dir/\».\»temp.jpg\»)] liefert -> file
» ;
?>