php get directory list
How to read a list of files from a folder using PHP? [closed]
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
I want to read a list the names of files in a folder in a web page using php. is there any simple script to acheive it?
9 Answers 9
The simplest and most fun way (imo) is glob
But the standard way is to use the directory functions.
There are also the SPL DirectoryIterator methods. If you are interested
There is this function scandir():
This is what I like to do:
If you have problems with accessing to the path, maybe you need to put this:
There is a glob. In this webpage there are good article how to list files in very simple way:
Check in many folders :
Folder_1 and folder_2 are name of folders, from which we have to select files.
$format is required format.
You can use standard directory functions
There is also a really simple way to do this with the help of the RecursiveTreeIterator class, answered here: https://stackoverflow.com/a/37548504/2032235
Not the answer you’re looking for? Browse other questions tagged php file or ask your own question.
Linked
Related
Hot Network Questions
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
PHP: список файлов и директорий
В данном уроке мы разберемся с типовой задачей, которая возникает во время работы над проектом PHP: получение списка файлов и директорий. Обсудим несколько базовых и более изощренных подходов, с перечисление плюсов и минусов каждого. Первые три решения будут использовать типовые функции PHP, а затем представим более надежное с применением итераторов SPL.
Для предметного обсуждения решения и демонстраций предположим, что структура директорий имеет следующий вид:
Базовые решения
Использование glob()
Первое решение базируется на использовании функции glob(), которая позволяет выполнять поиск пути с помощью шаблонов. Функция имеет два параметра:
Рассмотрим примеры. Для поиска в директории всех файлов и директорий, имена которых заканчиваются на .txt, следует использовать код:
Если нужен список файлов и директорий, имена которых начинаются на “te”, то код будет выглядеть так:
А для получения списка только директорий с именами, содержащих “ma”, используем код:
Последний пример выведет:
Обратите внимание, что в последнем примере использован флаг GLOB_ONLYDIR в качестве второго параметра функции. Поэтому файл master.dat исключен из списка. Хотя функция glob() очень проста в использовании, иногда она недостаточно гибкая. Например, нет флага для получения только файлов (без директорий), которые соответствуют шаблону.
Ниже приведенный пример возвращает список имен файлов и директорий начинающихся на “te”:
Второй пример выводит только файлы, содержащиеся в заданном каталоге.
Пример выдаст следующее:
Использование scandir()
Данный пример показывает, как получить список файлов и каталогов, имена которых начинаются на “te”:
Воспользуемся итераторами SPL
Теперь рассмотрим использование итераторов SPL. Но прежде, чем приступить к решению нашей задачи, проведем введение в библиотеку SPL и итераторы. Библиотека SPL предоставляет серию классов для объектно ориентированных структур данных, итераторов, дескрипторов файлов и прочее.
Конечно, PHP представляет возможность для получения такой информации с помощью функций,например filesize() и fileowner(). Но PHP5 основан на использовании концепции ООП. Поэтому лучше использовать современные методы работы с языком программирования. На нашем сайте есть уроки, посвященные работе с итераторами.
Реальное различие в данных итераторах заключается в их использовании для навигации по заданному пути.
FilesystemIterator
Использовать FilesystemIterator очень просто. Рассмотрим в действии. Представляем два примера. Первый показывает поиск всех файлов и каталогов, имена которых начинаются на “te”. Второй пример использует другой итератор RegexIterator для поиска всех файлов и каталогов, имена которых заканчиваются на “t.dat” или “t.php”. Итератор RegexIterator используется для фильтрации результата на основе регулярных выражений.
Выше приведенный код выдаст результат, аналогичный предыдущим примерам.
Второй пример с применением RegexIterator :
RecursiveDirectoryIterator
GlobIterator
Заключение
В данном уроке демонстрируется использование различных подходов для достижение одинаковой цели: получение списка файлов и директорий. Следует запомнить следующие ключевые моменты:
Данный урок подготовлен для вас командой сайта ruseller.com
Источник урока: phpmaster.com/list-files-and-directories-with-php/
Перевел: Сергей Фастунов
Урок создан: 13 Ноября 2012
Просмотров: 106920
Правила перепечатки
5 последних уроков рубрики «PHP»
Фильтрация данных с помощью zend-filter
Когда речь идёт о безопасности веб-сайта, то фраза «фильтруйте всё, экранируйте всё» всегда будет актуальна. Сегодня поговорим о фильтрации данных.
Контекстное экранирование с помощью zend-escaper
Обеспечение безопасности веб-сайта — это не только защита от SQL инъекций, но и протекция от межсайтового скриптинга (XSS), межсайтовой подделки запросов (CSRF) и от других видов атак. В частности, вам нужно очень осторожно подходить к формированию HTML, CSS и JavaScript кода.
Подключение Zend модулей к Expressive
Expressive 2 поддерживает возможность подключения других ZF компонент по специальной схеме. Не всем нравится данное решение. В этой статье мы расскажем как улучшили процесс подключение нескольких модулей.
Совет: отправка информации в Google Analytics через API
Предположим, что вам необходимо отправить какую-то информацию в Google Analytics из серверного скрипта. Как это сделать. Ответ в этой заметке.
Подборка PHP песочниц
Подборка из нескольких видов PHP песочниц. На некоторых вы в режиме online сможете потестить свой код, но есть так же решения, которые можно внедрить на свой сайт.
PHP Get all subdirectories of a given directory
16 Answers 16
you can use glob() with GLOB_ONLYDIR option
Here is how you can retrieve only directories with GLOB:
The Spl DirectoryIterator class provides a simple interface for viewing the contents of filesystem directories.
Almost the same as in your previous question:
Replace strtoupper with your desired function.
Example to show all:
You can try this function (PHP 7 required)
Inspired by Laravel
The following recursive function returns an array with the full list of sub directories
You can use the glob() function to do this.
Find all PHP files recursively. The logic should be simple enough to tweak and it aims to be fast(er) by avoiding function calls.
This is the one liner code:
Non-recursively List Only Directories
The only question that direct asked this has been erroneously closed, so I have to put it here.
It also gives the ability to filter directories.
If you’re looking for a recursive directory listing solutions. Use below code I hope it should help you.
Find all the files and folders under a specified directory.
Sample :
Not the answer you’re looking for? Browse other questions tagged php list get subdirectory or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
scandir
scandir — List files and directories inside the specified path
Description
Parameters
The directory that will be scanned.
For a description of the context parameter, refer to the streams section of the manual.
Return Values
Returns an array of filenames on success, or false on failure. If directory is not a directory, then boolean false is returned, and an error of level E_WARNING is generated.
Examples
Example #1 A simple scandir() example
The above example will output something similar to:
Notes
A URL can be used as a filename with this function if the fopen wrappers have been enabled. See fopen() for more details on how to specify the filename. See the Supported Protocols and Wrappers for links to information about what abilities the various wrappers have, notes on their usage, and information on any predefined variables they may provide.
See Also
User Contributed Notes 36 notes
Easy way to get rid of the dots that scandir() picks up in Linux environments:
Here is my 2 cents. I wanted to create an array of my directory structure recursively. I wanted to easely access data in a certain directory using foreach. I came up with the following:
How i solved problem with ‘.’ and ‘..’
I needed to find a way to get the full path of all files in the directory and all subdirectories of a directory.
Here’s my solution: Recursive functions!
Needed something that could return the contents of single or multiple directories, recursively or non-recursively,
for all files or specified file extensions that would be
accessible easily from any scope or script.
scandir() with regexp matching on file name and sorting options based on stat().
name file name
dev device number
ino inode number
mode inode protection mode
nlink number of links
uid userid of owner
gid groupid of owner
rdev device type, if inode device *
size size in bytes
atime time of last access (Unix timestamp)
mtime time of last modification (Unix timestamp)
ctime time of last inode change (Unix timestamp)
blksize blocksize of filesystem IO *
blocks number of blocks allocated
Scandir on steroids:
For when you want to filter your file list, or only want to list so many levels of subdirectories.
List all the files and folders in a Directory with PHP recursive function
I’m trying to go through all of the files in a directory, and if there is a directory, go through all of its files and so on until there are no more directories to go to. Each and every processed item will be added to a results array in the function below. It is not working though I’m not sure what I can do/what I did wrong, but the browser runs insanely slow when this code below is processed, any help is appreciated, thanks!
19 Answers 19
Your code :
Output (example) :
This will bring you all the files with paths.
It’s shorter version :
Your code :
Output (example) :
James Cameron’s proposition.
This could help if you wish to get directory contents as an array, ignoring hidden files and directories.
The result would be something like;
My proposal without ugly «foreach» control structures is
You may only want to extract the filepath, which you can do so by:
Still 4 lines of code, but more straight forward than using a loop or something.
Here is what I came up with and this is with not much lines of code
It outputs something like
** The dots are the dots of unoordered list.
Here’s a modified version of Hors answer, works slightly better for my case, as it strips out the base directory that is passed as it goes, and has a recursive switch that can be set to false which is also handy. Plus to make the output more readable, I’ve separated the file and subdirectory files, so the files are added first then the subdirectory files (see result for what I mean.)
Enjoy! Okay, back to the program I’m actually using this in.
UPDATE Added extra argument for including directories in the file list or not (remembering other arguments will need to be passed to use this.) eg.
$results = get_filelist_as_array($dir, true, », true);