php get files in directory

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

php get files in directory. Смотреть фото php get files in directory. Смотреть картинку php get files in directory. Картинка про php get files in directory. Фото php get files in directory

php get files in directory. Смотреть фото php get files in directory. Смотреть картинку php get files in directory. Картинка про php get files in directory. Фото php get files in directory

There is this function scandir():

This is what I like to do:

php get files in directory. Смотреть фото php get files in directory. Смотреть картинку php get files in directory. Картинка про php get files in directory. Фото php get files in directory

php get files in directory. Смотреть фото php get files in directory. Смотреть картинку php get files in directory. Картинка про php get files in directory. Фото php get files in directory

If you have problems with accessing to the path, maybe you need to put this:

php get files in directory. Смотреть фото php get files in directory. Смотреть картинку php get files in directory. Картинка про php get files in directory. Фото php get files in directory

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.

php get files in directory. Смотреть фото php get files in directory. Смотреть картинку php get files in directory. Картинка про php get files in directory. Фото php get files in directory

You can use standard directory functions

php get files in directory. Смотреть фото php get files in directory. Смотреть картинку php get files in directory. Картинка про php get files in directory. Фото php get files in directory

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

php get files in directory. Смотреть фото php get files in directory. Смотреть картинку php get files in directory. Картинка про php get files in directory. Фото php get files in directory

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.

Источник

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

php get files in directory. Смотреть фото php get files in directory. Смотреть картинку php get files in directory. Картинка про php get files in directory. Фото php get files in directory

This will bring you all the files with paths.

php get files in directory. Смотреть фото php get files in directory. Смотреть картинку php get files in directory. Картинка про php get files in directory. Фото php get files in directory

It’s shorter version :

php get files in directory. Смотреть фото php get files in directory. Смотреть картинку php get files in directory. Картинка про php get files in directory. Фото php get files in directory

Your code :

Output (example) :

James Cameron’s proposition.

php get files in directory. Смотреть фото php get files in directory. Смотреть картинку php get files in directory. Картинка про php get files in directory. Фото php get files in directory

php get files in directory. Смотреть фото php get files in directory. Смотреть картинку php get files in directory. Картинка про php get files in directory. Фото php get files in directory

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.

php get files in directory. Смотреть фото php get files in directory. Смотреть картинку php get files in directory. Картинка про php get files in directory. Фото php get files in directory

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

Источник

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
Просмотров: 106921
Правила перепечатки

5 последних уроков рубрики «PHP»

Фильтрация данных с помощью zend-filter

Когда речь идёт о безопасности веб-сайта, то фраза «фильтруйте всё, экранируйте всё» всегда будет актуальна. Сегодня поговорим о фильтрации данных.

php get files in directory. Смотреть фото php get files in directory. Смотреть картинку php get files in directory. Картинка про php get files in directory. Фото php get files in directory

Контекстное экранирование с помощью zend-escaper

Обеспечение безопасности веб-сайта — это не только защита от SQL инъекций, но и протекция от межсайтового скриптинга (XSS), межсайтовой подделки запросов (CSRF) и от других видов атак. В частности, вам нужно очень осторожно подходить к формированию HTML, CSS и JavaScript кода.

php get files in directory. Смотреть фото php get files in directory. Смотреть картинку php get files in directory. Картинка про php get files in directory. Фото php get files in directory

Подключение Zend модулей к Expressive

Expressive 2 поддерживает возможность подключения других ZF компонент по специальной схеме. Не всем нравится данное решение. В этой статье мы расскажем как улучшили процесс подключение нескольких модулей.

php get files in directory. Смотреть фото php get files in directory. Смотреть картинку php get files in directory. Картинка про php get files in directory. Фото php get files in directory

Совет: отправка информации в Google Analytics через API

Предположим, что вам необходимо отправить какую-то информацию в Google Analytics из серверного скрипта. Как это сделать. Ответ в этой заметке.

php get files in directory. Смотреть фото php get files in directory. Смотреть картинку php get files in directory. Картинка про php get files in directory. Фото php get files in directory

Подборка PHP песочниц

Подборка из нескольких видов PHP песочниц. На некоторых вы в режиме online сможете потестить свой код, но есть так же решения, которые можно внедрить на свой сайт.

Источник

PHP list of specific files in a directory

The following code will list all the file in a directory

While this is very simple code it does the job.

10 Answers 10

You’ll be wanting to use glob()

php get files in directory. Смотреть фото php get files in directory. Смотреть картинку php get files in directory. Картинка про php get files in directory. Фото php get files in directory

A simple way to look at the extension using substr and strrpos

You can also use the recursive variants of the iterators to traverse an entire directory hierarchy.

LIST FILES and FOLDERS in a directory (Full Code):
p.s. you have to uncomment the 5th line if you want only for specific extensions

php get files in directory. Смотреть фото php get files in directory. Смотреть картинку php get files in directory. Картинка про php get files in directory. Фото php get files in directory

you can mix between glob() function & pathinfo() function like below.

the below code will show files information for specific extension «pdf»

php get files in directory. Смотреть фото php get files in directory. Смотреть картинку php get files in directory. Картинка про php get files in directory. Фото php get files in directory

You should use glob.

More about using glob and advanced filtering:

But I’d recommend using glob instead too.

php get files in directory. Смотреть фото php get files in directory. Смотреть картинку php get files in directory. Картинка про php get files in directory. Фото php get files in directory

You can extend the RecursiveFilterIterator class like this:

Now you can instantiate RecursiveDirectoryIterator with path as an argument like this:

This will list files under the current folder only.

Now run the foreach loop on this iterator. You will get the files with specified extension

Note:— Also make sure to run the ExtensionFilter before RecursiveIteratorIterator, otherwise you will get all the files

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *