Browse directory recursively and get files name - php

I have to do a php script who browse a directory with sub-directory.
For each subdirectory (and maybe sub-subdirectory), I have to get filename and his parents directories.
Do you have a simple solution to do this please?
Thanks

Since I've had to create the same functionality for a website of mine too, I'll post my function as reference.
function recursiveFileSearch($path, $searchmask = "*") {
$path = rtrim($path, '/');
$files = array();
if(is_array($searchmask)) {
for($i = 0; $i < count($searchmask); $i++) {
$files = array_merge($files, glob($path.'/'.$searchmask[$i]));
}
sort($files);
} else {
$files = glob($path.'/'.$searchmask);
}
$dirs = glob($path.'/*', GLOB_ONLYDIR);
foreach($dirs as $dir) {
if(is_dir($dir)) {
$files = array_merge($files, recursiveFileSearch($dir, $searchmask));
}
}
sort($files);
return $files;
}

I am not 100% sure what you are asking, but if you take a look at the scandir documentation the first comment has a very useful recursive scanning function.
<?php
function dirToArray($dir) {
$result = array();
$cdir = scandir($dir);
foreach ($cdir as $key => $value)
{
if (!in_array($value,array(".","..")))
{
if (is_dir($dir . DIRECTORY_SEPARATOR . $value))
{
$result[$value] = dirToArray($dir . DIRECTORY_SEPARATOR . $value);
}
else
{
$result[] = $value;
}
}
}
return $result;
}
?>
The results will have the following format.
Array
(
[subdir1] => Array
(
[0] => file1.txt
[subsubdir] => Array
(
[0] => file2.txt
[1] => file3.txt
)
)
[subdir2] => Array
(
[0] => file4.txt
}
)

Related

How to Fetch Dynamic Multidimensional Array Elements and Display It Like a Path Name?

I have dynamic multidimensional array that contain directory, sub-directory and file names in a project folder, key indicating a sub-directory name and value indicating file names, if a key equal to number indicating only file and then if a key hasn't any value indicating there is no file at all in a directory. The array look like this :
Array
(
[0] => index.php
[src] => Array
(
[src2] => Array
(
[src3] => Array
(
[0] => test_src3.php
)
[0] => Array
(
[0] => test_src2.php
)
)
[0] => test_src.php
)
[src_test] => Array
(
[New Folder] => Array
(
)
[src_test2] => Array
(
[New Folder] => Array
(
)
[src_test3] => Array
(
)
)
)
[1] => test.php
)
The number of dimensions might be change based on sub directories that found in a folder path inputted by user (this program is used by a person in their local).
How could i fetch those array elements so that the result would be like this :
array(
[0] => src/src2/src3/
[1] => src_test/New Folder/
[2] => src_test/src_test2/New Folder/
[3] => src_test/src_test2/src_test3/
)
By the way i have a function to achieve this :
<?php
// Get specific element where the first index is 1 instead of 0
function getAtPos($tmpArray,$pos) {
$keys = array_keys($tmpArray);
return array($keys[$pos-1] => $tmpArray[$keys[$pos-1]]);
}
// Get all Keys that has String type only
function getKeyStr(array $mixed, $numbIdx){
$results = [];
$tmp = array_keys($mixed);
$ii = 0;
for ($i=1; $i <= $numbIdx; $i++) {
$keyArr = getAtPos($tmp, $i);
if (is_string($keyArr[$ii])) {
$results[] = $keyArr[$ii];
}
$ii++;
}
return $results;
}
function getKeyPaths(array $tree, $glue = '/', $return_array = true){
$paths = "";
$result = [];
foreach ($tree as $key => &$mixed) {
if (is_array($mixed) && !is_int($key)) {
$path = $key . $glue;
$retArrFalse = false;
$jlhMixed = count($mixed);
$getKeyStr = getKeyStr($mixed, $jlhMixed);
$jlhKeyStr = count($getKeyStr);
if ($jlhKeyStr < 2) {
$repeat = getKeyPaths($mixed, $glue, $retArrFalse);
$paths .= $path . $repeat;
if ($return_array) {
$paths .= "|";
}
}elseif($jlhKeyStr > 1) {
for ($i=0; $i < $jlhKeyStr; $i++) {
$idxAsso = $getKeyStr[$i];
$jlhKeySub = count($mixed[$idxAsso]);
$path2 = $idxAsso . $glue;
if ($jlhKeySub > 0) {
$paths .= $path . $path2 . getKeyPaths($mixed[$idxAsso], $glue, $retArrFalse);
if ($return_array) {
$paths .= "|";
}
}else{
$paths .= $path . $path2;
if ($return_array) {
$paths .= "|";
}
} // END of if else
} // END of for loop
} // END of elseif
}
} // END of foreach
if ($return_array) {
return explode("|", trim($paths, "|"));
}
return $paths;
}
the above function does not result like what i expected:
Array
(
[0] => src/src2/src3/
[1] => src_test/New Folder/
[2] => src_test/src_test2/New Folder/src_test3/
)
How do i achieve this ?
Any help would be appreciated !
UPDATE
I have modified my function trying to solve this:
<?php
// To get spesific element on dynamic associative array
function getAtPos($tmpArray,$pos) { // $pos is an index order starting with 1 instead of 0
$keys = array_keys($tmpArray);
return array($keys[$pos-1] => $tmpArray[$keys[$pos-1]]);
}
// Get key string type (associative) only in the given array
function getKeyStr(array $mixed, $numbIdx){
$results = [];
$tmp = array_keys($mixed); // change key to element (as array number).
$ii = 0;
for ($i=1; $i <= $numbIdx; $i++) {
$keyArr = getAtPos($tmp, $i);
if (is_string($keyArr[$ii])) {
$results[] = $keyArr[$ii];
}
$ii++;
}
return $results; // Return all second dimension sub-keys of the given array (parent)
}
// EDITED !
function getKeyPaths2(array $tree, $glue = '/', $return_array = true, $goToIfElse = false, $saveSameParent = []){
$paths = "";
$result = [];
$iFor = 0;
foreach ($tree as $key => &$mixed) {
if (is_array($mixed) && !is_int($key)) {
$path = $key . $glue;
$retArrFalse = false;
$jlhMixed = count($mixed);
$getKeyStr = getKeyStr($mixed, $jlhMixed); // Contain sub-keys of the second dimension of the parent
$jlhKeyStr = count($getKeyStr); // Count number of sub-keys of second dimension of parent
if ($goToIfElse !== false) {
$jlhKeyStr = $goToIfElse;
$iFor++;
unset($mixed);
$mixed = $tree;
$jlhMixed = count($mixed);
$getKeyStr = getKeyStr($mixed, $jlhMixed); // Contain sub-keys of the second dimension of the
$jlhKeyStr = count($getKeyStr); // Count number of sub-keys of second dimension of parent
}
if ($jlhKeyStr < 2) {
$repeat = getKeyPaths2($mixed, $glue, $retArrFalse);
$paths .= $path . $repeat;
if (!$return_array && $jlhKeyStr < 1) {
$paths .= "|";
}
}elseif($jlhKeyStr > 1) {
for ($i=$iFor; $i < $jlhKeyStr; $i++) {
$idxAsso = $getKeyStr[$i];
$jlhKeySub = count($mixed[$idxAsso]);
$path2 = $idxAsso . $glue;
if ($jlhKeySub > 0) {
$paths .= $path . $path2;
// TEST
$pecah = explode("|", $paths);
$saveSameParent[0] = end($pecah);
if ($return_array) {
$paths .= "|";
}
$paths .= $path . $path2 . getKeyPaths2($mixed[$idxAsso], $glue, $retArrFalse, $jlhKeyStr, $saveSameParent);
if ($return_array) {
$paths .= "|";
}
}else{
if ($goToIfElse !== false) {
$paths .= $path;
$paths .= "|";
$paths .= $saveSameParent[0] . $path2;
$paths .= "|";
}else{
$paths .= $path . $path2;
}
if ($return_array || $goToIfElse !== false) {
$paths .= "|";
}
} // END of if else
} // END of for loop
} // END of elseif
}
} // END of foreach
if ($return_array) {
return explode("|", trim($paths, "|"));
}
return $paths;
}
But this only works with my example array that i showed above.
If the given array like this, this would not work:
<?php
$tree = [];
$tree[0] = "index.php";
$tree["src"]["src2"]["src3"][0] = "test_src3.php";
$tree["src"]["src2"][0][0] = "test_src2.php";
$tree["src"][0] = "test_src.php";
$tree["src_test"]["New Folder"] = array();
$tree["src_test"]["src_test2"]["New Folder"] = array();
$tree["src_test"]["src_test2"]["src_test3.1"] = array();
$tree["src_test"]["src_test2"]["src_test3.2"] = array();
$tree["src_test"]["src_test2"]["src_test3.1"]["src_test3.1.1"] = array();
$tree["src_test"]["src_test2"]["src_test3.2"]["src_test3.2.1"]["src_test3.2.2"]["src_test3.2.3"] = array("test_src4.php", "test_src5.php");
The result would be :
Array
(
[0] => src/src2/src3/
[1] => src_test/New Folder/
[2] => src_test/src_test2/
[3] => src_test/src_test2/New Folder/src_test3.1/New Folder/src_test3.1/src_test3.1.1/src_test3.1.1/
[4] => New Folder/src_test3.2/New Folder/src_test3.2/src_test3.2.1/src_test3.2.1/src_test3.2.2/src_test3.2.3/
[5] => src_test3.1/src_test3.2/src_test3.1/src_test3.2/src_test3.2.1/src_test3.2.1/src_test3.2.2/src_test3.2.3/
)

Problem with getting file URLs of folders inside multiple directories

Here is my code to get a list of the file URLs inside a specific directory:
PHP
<?php
function getDirContents($directories, &$results = array()){
$files = array_diff(scandir($directories), array('..', '.'));;
foreach($files as $key => $value){
$path = $directories.DIRECTORY_SEPARATOR.$value;
if(is_dir($path)) {
getDirContents($path, $results);
} else {
$directory_path = basename($_SERVER['REQUEST_URI']);
$results[] = 'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
}
}
return $results;
}
$directories = "directory_A";
echo json_encode(getDirContents($directories));
The result for directory_A:
https://example.com/directory_A/voice1.mp3
https://example.com/directory_A/Media/inside_media_1/voice2.mp3
https://example.com/directory_A/Media/inside_media_1/voice3.mp3
What if we want to get URLs from multiple directories?
I tried to loop through those directories using a for loop like this:
<?php
function getDirContents($directories, &$results = array()){
$length = count($directories);
for ($i = 0; $i < $length; $i++) {
$files = array_diff(scandir($directories[$i]), array('..', '.'));;
foreach($files as $key => $value){
$path = $directories[$i].DIRECTORY_SEPARATOR.$value;
if(is_dir($path)) {
getDirContents($path, $results);
} else {
$directory_path = basename($_SERVER['REQUEST_URI']);
$results[] = 'https://' . $_SERVER['SERVER_NAME'] . str_replace($directory_path, "", $_SERVER['REQUEST_URI']) .$path;
}
}
}
return $results;
}
$directories = array("directory_A", "directory_B");
echo json_encode(getDirContents($directories));
But I only get the files inside those directories and code dosn't go to the folders inside each directory so I only get this for directory_A:
https://example.com/directory_A/voice1.mp3
What I'm missing and how to fix this?
You are passing an array and a string to the function. You have two options. You can always send in an array, or you can look for a string and convert it to an array.
class GoDir
{
/**
* Execute the console command.
*
* #return mixed
*/
public function handle()
{
$directories = array("storage", "config");
echo json_encode($this->getDirContents($directories));
}
public function getDirContents($directories, &$results = array())
{
// See if we got a string and convert to array
if ( is_string($directories) ) {
$directories = [$directories];
}
$length = count($directories);
for ($i = 0; $i < $length; $i++) {
$files = array_diff(scandir($directories[$i]), array('..', '.'));;
foreach($files as $key => $value){
$path = $directories[$i].DIRECTORY_SEPARATOR.$value;
if(is_dir($path)) {
$this->getDirContents($path, $results);
} else {
$directory_path = '/';
$results[] = $directory_path . $path;
}
}
}
return $results;
}
// Here is an alternative solution:
public function getDirContents($directories, &$results = array())
{
$length = count($directories);
for ($i = 0; $i < $length; $i++) {
$files = array_diff(scandir($directories[$i]), array('..', '.'));;
foreach($files as $key => $value){
$path = $directories[$i].DIRECTORY_SEPARATOR.$value;
if(is_dir($path)) {
// Turn the param into an array
$this->getDirContents([$path], $results);
} else {
$directory_path = '/';
$results[] = $directory_path . $path;
}
}
}
return $results;
}
}

Retreiving files based on a particular pattern

I am using this function to retreive files from directory and sub-directories.
How can I display only files with _lang.php within this directory and sub-directories?
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;
}
$dir = './test/';
var_dump(getDirContents($dir));
answered a question like this earlier, try using Iterator Classes
<?php
function getDirContents($directory, $pattern)
{
$result = array();
$objRecursiveDirectoryIterator = new RecursiveDirectoryIterator($directory, RecursiveDirectoryIterator::SKIP_DOTS);
$objRecursiveIteratorIterator = new RecursiveIteratorIterator($objRecursiveDirectoryIterator);
// use RegexIterator() to grab only files that match $pattern
$objRegexIterator = new RegexIterator($objRecursiveIteratorIterator, $pattern, RecursiveRegexIterator::GET_MATCH);
// iterate through all the results
foreach ($objRegexIterator as $arrMatches) {
$result[] = $arrMatches[0];
}
return $result;
}
$dir = './test/';
$arrDirContents = getDirContents($dir, "~^.+_lang\.php$~i");
var_dump($arrDirContents);

PHP oldest path based on a dir name

I have on my linux machine such folder tree structure:
/dir/yyyy/mm/dd/HH
e.g.:
/dir/2014/03/01/08
/dir/2014/03/20/09
/dir/2014/03/01/10
/dir/2014/08/01/10
/dir/2014/12/15/10
/dir/2015/01/01/14
I'd like to get in php what path is the oldest, like this:
The oldest path is: 2014-03-01 08
The newest path is: 2015-01-01 14
How it can be done?
It could be written better but it works
$paths = array(
'/dir/2014/03/01/08',
'/dir/2014/03/20/09',
'/dir/2014/03/01/10',
'/dir/2014/08/01/10',
'/dir/2014/12/15/10',
'/dir/2015/01/01/14',
);
$dates = array();
foreach($paths as $path)
{
$matches = array();
preg_match('#([^\/]+?)\/([^\/]+?)\/([^\/]+?)\/([^\/]+?)\/([^\/]+)#', $path, $matches);
$dates[$path] = strtotime(sprintf("%s-%s-%s %s:00:00", $matches[2], $matches[3], $matches[4], $matches[5]));
}
asort($dates);
$dates = array_keys($dates);
$oldest = array_shift($dates);
$newest = array_pop($dates);
It changes date find by regex to unixtimestamp then sorts it and returns top and bottom value of sorted array.
Little bit like Pascal style)
<?php
$oldest = '';
$newest = '';
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('./dir/'));
foreach ($iterator as $file => $object) {
if ($iterator->getDepth() === 4) {
$name = $object->getPath();
if ($name > $newest) {
$newest = $name;
}
if (empty($oldest) or $name < $oldest) {
$oldest = $name;
}
}
}
var_export([$oldest, $newest]);
Result:
array (
0 => './dir/2014/03/01/08',
1 => './dir/2015/01/01/14',
)
All you have to do is loop through each folder and find the directory that has the lowest number. If you have the file paths stored in a database, it can be easier, but from your question it seems like you want to search the folders.
<?php
$base = 'dir';
$yearLowest = lowestDir($base);
$monthLowest = lowestDir($yearLowest);
$dayLowest = lowestDir($monthLowest);
echo $dayLowest;
function lowestDir($dir) {
$lowest = null;
$handle = opendir($dir);
while(($name = readdir($handle))) {
if($name == '.' || $name == '..') {
continue;
}
if(is_dir($dir.'/'.$name) && ($lowest == null || $name < $lowest)) {
$lowest = $name;
}
}
closedir($handle);
return $dir.'/'.$lowest;
}
?>

Request uri in array

With a URI such as /test/test/test, I would like a way to create an array from $__SERVER['request_uri'] such as this:
[0] => '/' [1] => /test/ [2] => /test/test/ [3] => /test/test/test/
Any help would be appreciated!
A quick an dirty script I just created for you:
<?
$path = "/test/test2/test3";
$arr = explode("/", $path);
$arraynew = array();
$i=0;
foreach ($arr as $k => $v) {
if (($k==0) && ($v=="")) {
$arraynew[$i] = "/";
$i++;
continue;
}
if ($i == 1) {
$arraynew[$i] = $arraynew[$i-1] . $v;
} else {
$arraynew[$i] = $arraynew[$i-1] . "/" . $v;
}
$i++;
}
print_r($arraynew);
?>
Or this one that's more clean and simple and adds "/" at the end:
<?
$path = "/test/test2/test3";
$arr = explode("/", $path);
$arraynew = array();
$i=0;
foreach ($arr as $k => $v) {
$i > 0 ? $arraynew[] = $arraynew[$i-1] . $v . "/" : $arraynew[] = "/";
$i++;
}
print_r($arraynew);
?>
Look up the dirname() function.
It gives you the parent directory of any given filename or directory name.
In your case, simply use it repeatedly (in a loop) to get each successive parent folder name.

Categories