there,
I tried many time to put the answer from the recursive function inside an array ($result) but I couldn't. Here the code:
function readDirs($path , $result = [])
{
$dirHandle = opendir($path);
while($item = readdir($dirHandle))
{
$newPath = $path."/".$item;
if(is_dir($newPath) && $item != '.' && $item != '..')
{
readDirs($newPath, $result);
}
elseif(!is_dir($newPath) && $item != '.DS_Store' && $item != '.' && $item != '..')
{
echo "$path<br>";
$result[] = $path;
return $result;
}
}
}
$path = "/Users/mycomputer/Documents/www/Photos_projets";
$results = array();
readDirs($path, $results);
Can you help me to put the path inside the array, because I need them later in my code?
Thank's
I cant understand your question but for sure this may be help
function readDirs($path)
{
$result = [];
$dirHandle = opendir($path);
while($item = readdir($dirHandle))
{
$newPath = $path."/".$item;
if(is_dir($newPath) && $item != '.' && $item != '..')
{
$result[] = readDirs($newPath);
}
elseif(!is_dir($newPath) && $item != '.DS_Store' && $item != '.' && $item != '..')
{
echo "$path<br>";
$result[] = $path;
return $result; //im not sure this return statement you implement is needed try it to remove it if this does not work
}
}
return $result;
}
$path = "/Users/mycomputer/Documents/www/Photos_projets";
$result = readDirs($path);
var_dump($result);
try it and response.
Related
Last time I noticed 2 kind of errors when trying to load the list of images in my uploads folder with Roxy Fileman:
Error loading php/fileslist.php?d=%2Fadmin%2Fuploads&type=image
and sometimes only this error:
E_LoadingAjax php/dirtree.php
So once I have the first error, another time second error after I try to refresh the filemanager window.
After 2nd or 3rd refresh it suddenly works and the files are loaded and shown, but those errors are coming up each time I open the filemanager. randomly they are gone and some time it works, I am not sure what is causing this.
This is the content of filelist.php:
verifyAction('FILESLIST');
checkAccess('FILESLIST');
$path = (empty($_POST['d'])? getFilesPath(): $_POST['d']);
$type = (empty($_POST['type'])?'':strtolower($_POST['type']));
if($type != 'image' && $type != 'flash')
$type = '';
verifyPath($path);
$files = listDirectory(fixPath($path), 0);
natcasesort($files);
$str = '';
echo '[';
foreach ($files as $f){
$fullPath = $path.'/'.$f;
if(!is_file(fixPath($fullPath)) || ($type == 'image' && !RoxyFile::IsImage($f)) || ($type == 'flash' && !RoxyFile::IsFlash($f)))
continue;
$size = filesize(fixPath($fullPath));
$time = filemtime(fixPath($fullPath));
$w = 0;
$h = 0;
if(RoxyFile::IsImage($f)){
$tmp = #getimagesize(fixPath($fullPath));
if($tmp){
$w = $tmp[0];
$h = $tmp[1];
}
}
$str .= '{"p":"'.mb_ereg_replace('"', '\\"', $fullPath).'","s":"'.$size.'","t":"'.$time.'","w":"'.$w.'","h":"'.$h.'"},';
}
$str = mb_substr($str, 0, -1);
echo $str;
echo ']';
And this is dirtree.php:
function getFilesNumber($path, $type){
$files = 0;
$dirs = 0;
$tmp = listDirectory($path);
foreach ($tmp as $ff){
if($ff == '.' || $ff == '..')
continue;
elseif(is_file($path.'/'.$ff) && ($type == '' || ($type == 'image' && RoxyFile::IsImage($ff)) || ($type == 'flash' && RoxyFile::IsFlash($ff))))
$files++;
elseif(is_dir($path.'/'.$ff))
$dirs++;
}
return array('files'=>$files, 'dirs'=>$dirs);
}
function GetDirs($path, $type){
$ret = $sort = array();
$files = listDirectory(fixPath($path), 0);
foreach ($files as $f){
$fullPath = $path.'/'.$f;
if(!is_dir(fixPath($fullPath)) || $f == '.' || $f == '..')
continue;
$tmp = getFilesNumber(fixPath($fullPath), $type);
$ret[$fullPath] = array('path'=>$fullPath,'files'=>$tmp['files'],'dirs'=>$tmp['dirs']);
$sort[$fullPath] = $f;
}
natcasesort($sort);
foreach ($sort as $k => $v) {
$tmp = $ret[$k];
echo ',{"p":"'.mb_ereg_replace('"', '\\"', $tmp['path']).'","f":"'.$tmp['files'].'","d":"'.$tmp['dirs'].'"}';
GetDirs($tmp['path'], $type);
}
}
$type = (empty($_GET['type'])?'':strtolower($_GET['type']));
if($type != 'image' && $type != 'flash')
$type = '';
echo "[\n";
$tmp = getFilesNumber(fixPath(getFilesPath()), $type);
echo '{"p":"'. mb_ereg_replace('"', '\\"', getFilesPath()).'","f":"'.$tmp['files'].'","d":"'.$tmp['dirs'].'"}';
GetDirs(getFilesPath(), $type);
echo "\n]";
What I tried:
checked if php-mbstring module is installed, yes it is
in fuctions.inc.php there is a function:
function listDirectory ($ path) {
$ ret = #scandir ($ path);
if ($ ret === false) {
$ ret = array ();
$ d = opendir ($ path);
if ($ d) {
while (($ f = readdir ($ d))! == false) {
$ ret [] = $ f;
}
closedir ($ d);
}
}
I replaced #scandir with scandir there, did not help.
in system.inc.php is this:
define('BASE_PATH', dirname (FILE));
date_default_timezone_set('UTC');
mb_internal_encoding("UTF-8");
mb_regex_encoding(mb_internal_encoding());
I replaced define('BASE_PATH', dirname (__FILE__)); to define('BASE_PATH', (__DIR__));
Did not help. No more ideas. The dev tools Network neither Console section doesn't show any error.
I want to ask - How can I return/make array with-in a foreach loop?
Here is my code
function getAllUsers() {
$dir = "users/";
$fl = scandir($dir);
$cnt = 0;
foreach (scandir($dir) as $fl) {
if ($fl !== '.') {
if ($fl !== '..') {
if ($fl !== 'index.php') {
$pr = $fl;
$fl1 = scandir($dir . '/' . $fl);
$cnt++;
return $fl1[3]; //Here I want a array for file inside 'users\'.
}
}
}
}
}
Thanks for giving answer.
Basically: you can not.
upon using return, the current function returns the value and stops execution.
return is by definition the end of the function.
but you can save the data you want to return in an array and then return the whole thing:
function getAllUsers() {
$dir = "users/";
$fl = scandir($dir);
$cnt = 0;
$result = []; //initiating the array
foreach (scandir($dir) as $fl) {
if ($fl !== '.') {
if ($fl !== '..') {
if ($fl !== 'index.php') {
$pr = $fl;
$fl1 = scandir($dir . '/' . $fl);
$cnt++;
$result[] = $fl1[3]; //adding your value to the array
}
}
}
}
return $result;
}
Edit: If your PHP-Version mucks about the $result = []; you can use the "old" style $result = array(); instead
Generators: Solution for PHP >= 5.5.
If you want the function to return a value for each element in the loop back from the function use a generator:
/**
* #return Generator|Iterator
*/
function getAllUsers() {
$dir = "users/";
$fl = scandir($dir);
$cnt = 0;
foreach (scandir($dir) as $fl) {
if ($fl !== '.') {
if ($fl !== '..') {
if ($fl !== 'index.php') {
$pr = $fl;
$fl1 = scandir($dir . '/' . $fl);
$cnt++;
yield $fl1[3]; //Here I want a array for file inside 'users\'.
}
}
}
}
}
// Loop over
foreach (getAllUsers() as $file) {
}
// Or one at a time
$generator = getAllUsers();
$file1 = $generator->current();
The other solutions here are more feasible however, this solution is mostly useful for implementing the IteratorAggregate interface, or creating co-routines.
You can achieve this by using an array. like below..
function getAllUsers() {
$dir = "users/";
$fl = scandir($dir);
$cnt = 0;
$array = array();
foreach (scandir($dir) as $fl) {
if ($fl !== '.') {
if ($fl !== '..') {
if ($fl !== 'index.php') {
$pr = $fl;
$fl1 = scandir($dir . '/' . $fl);
$cnt++;
$array[$fl] = $fl1[3]; //Push values in array for each user.
}
}
}
}
return $array;
}
Hope this will help
I want to display the subfolder names in a folder contained .
How can i do this using php code?
This is the code:
function read_folder_directory($dir)
{
$listDir = array();
if($handler = opendir($dir)) {
while (($sub = readdir($handler)) !== FALSE) {
if ($sub != "." && $sub != ".." && $sub != "Thumb.db" && $sub != "Thumbs.db") {
if(is_file($dir."/".$sub)) {
$listDir[] = $sub;
}elseif(is_dir($dir."/".$sub)){
$listDir[$sub] = $this->read_folder_directory($dir."/".$sub);
}
}
}
closedir($handler);
}
return $listDir;
}
When iam using this i get all file names also.I need only folder names.
Remove the is_file part
function read_folder_directory($dir)
{
$listDir = array();
if($handler = opendir($dir)) {
while (($sub = readdir($handler)) !== FALSE) {
if ($sub != "." && $sub != ".." && $sub != "Thumb.db" && $sub != "Thumbs.db") {
if(is_dir($dir."/".$sub)){
$listDir[$sub] = $this->read_folder_directory($dir."/".$sub);
}
}
}
closedir($handler);
}
return $listDir;
}
The function below returns an array of XML files from a given directory including all subdirectories. How can I modify this function by passing a second optional parameter which excludes a directory.
E.g:
getDirXmlFiles($config_dir, "example2");
Directory/Files
/file1.xml
/file2.xml
/examples/file3.xml
/examples/file4.xml
/example2/file5.xml
/example2/file5.xml
In the above case the function would return all files except files in the example2 directory.
function getDirXmlFiles($base) {
$files = array();
if(!is_dir($base)) return $files;
if ($handle = opendir($base)) {
while (false !== ($file = readdir($handle))) {
if ($file == "." || $file == "..") continue;
if(is_dir("$base/$file")) {
$subfiles = $this->getDirXmlFiles("$base/$file");
$files = array_merge($files, $subfiles);
} else {
if(Cms_File::type($file,false) == "xml")
$files[] = "$base/$file";
}
}
closedir($handle);
}
return $files;
}
Try this:
function getDirXmlFiles($base, $exclude = NULL) {
$files = array();
if(!is_dir($base)) return $files;
if ($handle = opendir($base)) {
while (false !== ($file = readdir($handle))) {
if ($file == "." || $file == ".." || "$base/$file" == $exclude) continue;
if(is_dir("$base/$file")) {
$subfiles = $this->getDirXmlFiles("$base/$file",$exclude);
$files = array_merge($files, $subfiles);
} else {
if(Cms_File::type($file,false) == "xml")
$files[] = "$base/$file";
}
}
closedir($handle);
}
return $files;
}
Redefine the function inputs:
function getDirXmlFiles($base, $excludeDir) {
Then change this line:
if(is_dir("$base/$file")) {
to this:
if(is_dir("$base/$file") && "$base/$file" != "$base/$excludeDir") {
You can just slightly modify the function to check and see if the current directory is the one you want to exclude or not
function getDirXmlFiles($base,$exclude) {
$files = array();
if(!is_dir($base)) return $files;
if ($handle = opendir($base)) {
while (false !== ($file = readdir($handle))) {
if ($file == "." || $file == "..") continue;
if(is_dir("$base/$file") && $file != $exclude) {
$subfiles = $this->getDirXmlFiles("$base/$file",$exclude);
$files = array_merge($files, $subfiles);
} else {
if(Cms_File::type($file,false) == "xml")
$files[] = "$base/$file";
}
}
closedir($handle);
}
return $files;
}
Smth of the sort ( tested only the syntax validation there might be needed some small debugging ) ( this will allow you to exclude multiple directory names )
function getDirXmlFiles($base, $excludeArray = array()) {
if (!is_array($excludeArray))
throw new Exception(__CLASS__ . "->" . __METHOD__ . " expects second argument to be a valid array");
$files = array();
if(!is_dir($base)) return $files;
if ($handle = opendir($base)) {
while (false !== ($file = readdir($handle))) {
$path = $base . "/" . $file;
$isDir = is_dir($path);
if (
$file == "."
|| $file == ".."
|| (
$isDir
&& count($excludeArray) > 0
&& in_array($file, $excludeArray)
)
)
continue;
if($isDir) {
$subfiles = $this->getDirXmlFiles($path, $excludeArray);
$files = array_merge($files, $subfiles);
} else {
if(Cms_File::type($file,false) == "xml")
$files[] = $path;
}
}
closedir($handle);
}
return $files;
}
This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
php scandir --> search for files/directories
I have a folder, inside this folder, have many subfolders, but I would like to scan all the subfolders, and scan all the .m file... How can I do so??
Here is the file:
/MyFilePath/
/myPath.m
/myPath2.m
/myPath3.m
/MyClasses/
/my.m
/my1.m
/my2.m
/my3.m
/Utilities/
/u1.m
/u2.m
/External/
/a.m
/b.m
/c.m
/Internal/
/d.m
/e.m
/f.m
/Views/
/a_v.m
/b_v.m
/c_v.m
/Controllers/
/a_vc.m
/b_vc.m
/c_vc.m
/AnotherClasses/
/anmy.m
/anmy1.m
/anmy2.m
/anmy3.m
/Networking/
/net1.m
/net2.m
/net3.m
/External/
/Internal/
/Views/
/Controllers/
You could also use some of the SPL's iterators. A quick and basic example would look like:
$directories = new RecursiveDirectoryIterator('path/to/search');
$flattened = new RecursiveIteratorIterator($directories);
$filter = new RegexIterator($flattened, '/\.in$/');
foreach ($filter as $file) {
echo $file, PHP_EOL;
}
More infos (mostly incomplete):
http://php.net/recursivedirectoryiterator
http://php.net/recursiveiteratoriterator
http://php.net/regexiterator
You can use a recursive function like this:
function searchFiles($dir,$pattern,$recursive=false)
{
$matches = array();
$d = dir($dir);
while (false !== ($entry = $d->read()))
{
if (is_dir($d->path.$entry) && $recursive)
{
$subdir = $d->path.$entry;
$matches = array_merge($matches,searchFiles($dir,$pattern,$recursive));
}
elseif (is_file($d->path.$entry) && preg_match($pattern,$entry))
{
$matches[] = $d->path.$entry;
}
}
$d->close();
return $matches;
}
Usage:
$matches = searchFiles("/mypath/","'[.]m$'i",true);
function ScanForMFiles($dir){
$return = array();
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
if(is_dir($dir.$file)){
$return = array_merge($return, ScanForMFiles($dir.$file."/"));
}
else {
if(substr($file, -2) == '.m')
$return[] = $file;
}
}
}
closedir($handle);
}
return $return;
}
var_dump(ScanForMFiles('./'));
You'll want to look to the PHP docs for details on this: http://php.net/manual/en/function.readdir.php
Here's an example that should do what you you want. It will return an array of all .m files in the sub directories. You can then loop through each file and read the contents if that is what you are interested in.
<?php
function get_m_files($root = '.'){
$files = array();
$directories = array();
$last_letter = $root[strlen($root)-1];
$root = ($last_letter == '\\' || $last_letter == '/') ? $root : $root.DIRECTORY_SEPARATOR;
$directories[] = $root;
while (sizeof($directories)) {
$dir = array_pop($directories);
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file == '.' || $file == '..') {
continue;
}
$file = $dir.$file;
if (is_dir($file)) {
$directory_path = $file.DIRECTORY_SEPARATOR;
array_push($directories, $directory_path);
} elseif (is_file($file)) {
if (substr( $file, -strlen( ".m" ) ) == ".m") {
$files[] = $file;
}
}
}
closedir($handle);
}
}
return $files;
}
?>