Recursive File Search (PHP)
<?php
$it = new RecursiveDirectoryIterator("L:\folder\folder\folder");
$display = Array ( 'jpeg', 'jpg' );
foreach(new RecursiveIteratorIterator($it) as $file)
{
if (in_array(strtolower(array_pop(explode('.', $file))), $display))
echo $file . "<br/> \n";
}
?>
List all the files and folders in a Directory with PHP recursive function
Get all the files and folders in a directory, don't call function when you have .
or ..
.
Your code :
<?php
function getDirContents($dir, &$results = array()) {
$files = scandir($dir);
foreach ($files as $key => $value) {
$path = realpath($dir . DIRECTORY_SEPARATOR . $value);
if (!is_dir($path)) {
$results[] = $path;
} else if ($value != "." && $value != "..") {
getDirContents($path, $results);
$results[] = $path;
}
}
return $results;
}
var_dump(getDirContents('/xampp/htdocs/WORK'));
Output (example) :
array (size=12)
0 => string '/xampp/htdocs/WORK/iframe.html' (length=30)
1 => string '/xampp/htdocs/WORK/index.html' (length=29)
2 => string '/xampp/htdocs/WORK/js' (length=21)
3 => string '/xampp/htdocs/WORK/js/btwn.js' (length=29)
4 => string '/xampp/htdocs/WORK/js/qunit' (length=27)
5 => string '/xampp/htdocs/WORK/js/qunit/qunit.css' (length=37)
6 => string '/xampp/htdocs/WORK/js/qunit/qunit.js' (length=36)
7 => string '/xampp/htdocs/WORK/js/unit-test.js' (length=34)
8 => string '/xampp/htdocs/WORK/xxxxx.js' (length=30)
9 => string '/xampp/htdocs/WORK/plane.png' (length=28)
10 => string '/xampp/htdocs/WORK/qunit.html' (length=29)
11 => string '/xampp/htdocs/WORK/styles.less' (length=30)
Find all .php files in folder recursively
just add something like:
function listFolderFiles($dir){
$ffs = scandir($dir);
$i = 0;
$list = array();
foreach ( $ffs as $ff ){
if ( $ff != '.' && $ff != '..' ){
if ( strlen($ff)>=5 ) {
if ( substr($ff, -4) == '.php' ) {
$list[] = $ff;
//echo dirname($ff) . $ff . "<br/>";
echo $dir.'/'.$ff.'<br/>';
}
}
if( is_dir($dir.'/'.$ff) )
listFolderFiles($dir.'/'.$ff);
}
}
return $list;
}
$files = array();
$files = listFolderFiles(dirname(__FILE__));
Recursively search all directories for an array of strings in php
If you're allowed to execute shell commands in your environment (and assuming you're running your script on *nix), you could call the native grep command recursively. That would give you the fastest results.
$contents_list = array("xyz","abc","hello");
$path = "/tmp/";
$pattern = implode('\|', $contents_list) ;
$command = "grep -r '$pattern' $path";
$output = array();
exec($command, $output);
foreach ($output as $match) {
echo $match . '\n';
}
If the disable_functions
directive is in effect and you can't call grep, you could use your approach with RecursiveDirectoryIterator
and reading the files line by line, using strpos on each line. Please note that strpos
requires a strict equality check (use !== false
instead of != false
), otherwise you'll skip matches at the beginning of a line.
A slightly faster way is to use glob recusively to obtain a list of files, and read those files at once instead of scanning them line by line. According to my tests, this approach will give you about 30-35% time advantage over yours.
function recursiveDirList($dir, $prefix = '') {
$dir = rtrim($dir, '/');
$result = array();
foreach (glob("$dir/*", GLOB_MARK) as &$f) {
if (substr($f, -1) === '/') {
$result = array_merge($result, recursiveDirList($f, $prefix . basename($f) . '/'));
} else {
$result[] = $prefix . basename($f);
}
}
return $result;
}
$files = recursiveDirList($path);
foreach ($files as $filename) {
$file_content = file($path . '/' . $filename);
foreach ($file_content as $line) {
foreach($contents_list as $content) {
if(strpos($line, $content) !== false) {
echo $line . '\n';
}
}
}
}
Credit for the recursive glob function goes to http://proger.i-forge.net/3_ways_to_recursively_list_all_files_in_a_directory/Opc
To sum it up, performance-wise you have the following rankings (results in seconds for a farly large directory containing ~1200 files recusively, using two common text patterns):
- call grep via exec() - 2.2015s
- use recursive
glob
and read files withfile()
- 9.4443s - use
RecursiveDirectoryIterator
and read files withreadline()
- 15.1183s
PHP: List all files in a folder recursively and fast
You could use the RecursiveDirectoryIterator
- but I doubt, it's faster than a simple recusive function.
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('/path/to/folder'));
foreach ($iterator as $file) {
if ($file->isDir()) continue;
$path = $file->getPathname();
}
PHP scandir recursively
You can scan directory recursively in this way the target is your top most directory:
function scanDir($target) {
if(is_dir($target)){
$files = glob( $target . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned
foreach( $files as $file )
{
scanDir( $file );
}
}
}
You can adapt this function for your need easily.
For example if would use this to delete the directory and its content you could do:
function delete_files($target) {
if(is_dir($target)){
$files = glob( $target . '*', GLOB_MARK ); //GLOB_MARK adds a slash to directories returned
foreach( $files as $file )
{
delete_files( $file );
}
rmdir( $target );
} elseif(is_file($target)) {
unlink( $target );
}
You can not do this in the way you are doing.
The following function gets recursively all the directories, sub directories so deep as you want and the content of them:
function assetsMap($source_dir, $directory_depth = 0, $hidden = FALSE)
{
if ($fp = @opendir($source_dir))
{
$filedata = array();
$new_depth = $directory_depth - 1;
$source_dir = rtrim($source_dir, '/').'/';
while (FALSE !== ($file = readdir($fp)))
{
// Remove '.', '..', and hidden files [optional]
if ( ! trim($file, '.') OR ($hidden == FALSE && $file[0] == '.'))
{
continue;
}
if (($directory_depth < 1 OR $new_depth > 0) && @is_dir($source_dir.$file))
{
$filedata[$file] = assetsMap($source_dir.$file.'/', $new_depth, $hidden);
}
else
{
$filedata[] = $file;
}
}
closedir($fp);
return $filedata;
}
echo 'can not open dir';
return FALSE;
}
Pass your path to the function:
$path = 'elements/images/';
$filedata = assetsMap($path, $directory_depth = 5, $hidden = FALSE);
$filedata is than an array with all founded directories and sub directories with their content. This function lets you scan the directories structure ($directory_depth) so deep as you want as well get rid of all the boring hidden files (e.g. '.','..')
All you have to do now is to use the returned array, which is the complete tree structure, to arrange the data in your view as you like.
What you are trying to do is in fact a kind of file manager and as you know there are a lot of those in the wild, open source and free.
I hope this will help you and I wish you a merry Christmas.
how to search for a line match from all files recursively found in a directory
use the command
find /var/www/projectDir/ -name '*.php'|xargs grep 'public function getProjectData('
the first portion
find /var/www/projectDir/ -name '*.php'
will search all the files which are having extension php
and within directory /var/www/projectDir
the second portion
xargs grep 'public function getProjectData('
will search all the files found in first portion for public function getProjectData(
.
xargs is used to consider the output of first portion as a standard input for second portion.
The symbol |
named pipe
will pipe the output to second portion
output
/var/www/projectDir/sub/directory/somephpfile.php: public function getProjectData($param1, $param2) {
now you can open the file and search for which line the content is defined using
(ctrl + F for gedit) or ( ctrl + W for nano)
or use any of your favorite editor.
Recursively search directories and list the x newest files (based on creation date on server)
You are on a good way. This should work for you:
First of all we create a RecursiveDirectoryIterator
which we pass to our RecursiveIteratorIterator
so we have an iterator to iterate recursively through all files of your specified path. We filter everything expect *.jpg
files out with a RegexIterator
.
Now we can convert the iterator into an array with iterator_to_array()
, so we can sort the array as we want to. Which we do with usort()
combined with filectime()
so we compare the creation date of the files and sort it by that.
At the end we can just slice the 30 newest files with array_slice()
and we are done. Loop through the files and display them.
Code:
<?php
$it = new RecursiveIteratorIterator(new RecursiveDirectoryIterator("your/path"));
$rgIt = new RegexIterator($it, "/^.+\.jpg$/i");
$files = iterator_to_array($rgIt);
usort($files, function($a, $b){
if(filectime($a) == filectime($b))
return 0;
return filectime($a) > filectime($b) ? -1 : 1;
});
$files = array_slice($files, 0 , 30);
foreach($files as $v)
echo $v . PHP_EOL;
?>
Related Topics
Setting Up Ssl on a Local Xampp/Apache Server
Passing Multiple PHP Variables to Shell_Exec()
Best Method for Sum Two Arrays
How to Use Array_Push on a Session Array in PHP
Php: Best Way to Check If Input Is a Valid Number
Finding the Minimum Value's Key in an Associative Array
Delete First 3 Characters and Last 3 Characters from String PHP
PHP Printed Boolean Value Is Empty, Why
How to Create a Subquery Using Laravel Eloquent
PHP Date() in Foreign Languages - E.G. Mar 25 Aoû 09
Difference Between PHP Echo and Return in Terms of a Jquery Ajax Call
Generate Cryptographically Secure Random Numbers in PHP
Highlight the Word in the String, If It Contains the Keyword
Create Blog Post Links Similar to a Folder Structure