0

How i can list all the files in a folder and its sub folders using php

4 Answers 4

6

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

Sign up to request clarification or add additional context in comments.

1 Comment

SELF_FIRST isn't particularly useful for listing files only and may confuse the OP.
0

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

I want to search a particular file in a folder and its sub folder when i am running a web page.
What do you need to search this file for exactly?
0

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

0

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.