How i can list all the files in a folder and its sub folders using php
4 Answers
You can make use of the SPL iterators. In particular the RecursiveDirectoryIterator which will recursively traverse through a given directory structure.
Like so:
$realpath = realpath('/path/to/file'); $fileObjects = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($realpath), RecursiveIteratorIterator::SELF_FIRST); foreach($fileObjects as $key => $object){ if($object->getFilename() === 'filename.png') { echo $object->getPathname(); } } The SELF_FIRST iteration mode basically tells the iterator that the parent items are to be placed first (parents come first).
1 Comment
SELF_FIRST isn't particularly useful for listing files only and may confuse the OP.Are you talking about for a php script running as its own program or a web application. Why would you need to do this?
echo shell_exec('find -name *'); But then you can really just run that in the shell.
If you want a web application to run this, www-data will need permissions to run that script and it is highly unsafe to let it do that. Instead you can have a user with appropriate permission log in and do that. Not quite as unsafe.
2 Comments
You can write a script to get all files in a folder(and subfolders) using php scandir in an array. Then you can search that array for your particular file.
Example:
<?php $dir = '/tmp'; $files = scandir($dir); print_r($files); ?> Output something like this:
Array ( [0] => . [1] => .. [2] => bar.php [3] => foo.txt [4] => somedir ) Comments
If you want to be able to specify a mask or something, like *.txt for all txt files then there is no better function than "glob" :)