File searching in a directory using php
How i can list all the files in a folder and its sub folders using php开发者_JAVA百科
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).
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.
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
)
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" :)
精彩评论