I took over this site for management. the former developer used opendir() which opens only one level before getting the files in the folder. I would like to create multi-level folders before the final files. I created the sub-folders on the server but I need to modify the code to dynamically recognise the sub-folders as folders not file.
if ($handle = opendir("parentfolder/".$pageid.'/')) {
$list = array();
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
$list[] = "$file\n";
}
}
rsort($list);
$clength = count($list);
for($x = 0; $x <$clength; $x++){
$pubFolders .= "<a href='".$maindomain."/reports/".$list[$x]."' class='imagefolders'><img src='".$maindomain."/images/icons/image.png' alt=''/><br>".$list[$x]."</a>";
}
$data = $data.$pubFolders;
closedir($handle);
}
Use glob() with GLOB_ONLYDIR; some example functions are as follows:
function findDirectories($rootPath) {
$directories = array();
foreach (glob($rootPath . "/*", GLOB_ONLYDIR) as $directory) {
$directories[] = $directory;
}
return $directories;
}
function findFiles($rootPath, $extension) {
$files = array();
foreach (glob($rootPath . "/*.$extension") as $file) {
$files[] = $file;
}
return $files;
}
function findFilesRecursive($rootPath,$extension) {
$files = findFiles($rootPath,$extension);
$directories = findDirectories($rootPath);
if (!empty($directories)) {
foreach ($directories as $key=>$directory) {
$foundFiles = findFilesRecursive($directory,$extension);
foreach ($foundFiles as $foundFile) {
$files[] = $foundFile;
}
}
}
return $files;
}
If you don't care about defining specific extensions, just pass in * as the $extension parameter.
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
hi all I have made a function
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(is_dir($path) && $value != "." && $value != "..") {
getDirContents($path, $results);
$results[] = $path;
}
}
return $results;
}
and I am calling it in like
$value = $this->getDirContents("/var/www/staging/public/files/rgerger");
way from my controller by I am uable to get the full details of the folder I mean the directories and the subdirectories with all contents ..
scandir is on only giving the folder under the target folder which is only scaned but this is not giving me the content of the child folder upto the end.
You need to assign the result of the recursive method call back to the caller.
My (untested) example
function getDirectoryContents($dir)
{
$files = [];
if (is_dir($dir)) {
foreach(scandir($dir) as $key => $fileName) {
$filePath = realpath($dir . DIRECTORY_SEPARATOR . $fileName);
if ($fileName == '.' || $fileName == '..') {
continue;
}
if (is_dir($filePath)) {
$files[] = getDirectoryContents($filePath);
} else {
$files[] = $fileName;
}
}
}
return $files;
}
As per my comment, you can also use the SPL RecursiveDirectoryIterator which is PHP's inbuilt OOP solution for iterating the file system.
$dir = '/master/files';
$files = scandir($dir);
foreach($files as $file){
if(($file != '.') && ($file != '..')){
if(is_dir($dir.'/'.$file)){
echo '<li class="folder">'.$file.'</li>';
}else{
echo '<li class="file">'.$file.'</li>';
}
}
}
From the script above, I get result:
images (folder)
index.html
javascript (folder)
style.css
How to sort the folder first and then files?
Try this :
$dir = '/master/files';
$directories = array();
$files_list = array();
$files = scandir($dir);
foreach($files as $file){
if(($file != '.') && ($file != '..')){
if(is_dir($dir.'/'.$file)){
$directories[] = $file;
}else{
$files_list[] = $file;
}
}
}
foreach($directories as $directory){
echo '<li class="folder">'.$directory.'</li>';
}
foreach($files_list as $file_list){
echo '<li class="file">'.$file_list.'</li>';
}
You don't need to make 2 loops, you can do the job with this piece of code:
<?php
function scandirSorted($path) {
$sortedData = array();
foreach(scandir($path) as $file) {
// Skip the . and .. folder
if($file == '.' || $file == '..')
continue;
if(is_file($path . $file)) {
// Add entry at the end of the array
array_push($sortedData, '<li class="folder">' . $file . '</li>');
} else {
// Add entry at the begin of the array
array_unshift($sortedData, '<li class="file">' . $file . '</li>');
}
}
return $sortedData;
}
?>
This function will return the list of entries of your path, folders first, then files.
Modifying your code as little as possible:
$folder_list = "";
$file_list = "";
$dir = '/master/files';
$files = scandir($dir);
foreach($files as $file){
if(($file != '.') && ($file != '..')){
if(is_dir($dir.'/'.$file)){
$folder_list .= '<li class="folder">'.$file.'</li>';
}else{
$file_list .= '<li class="file">'.$file.'</li>';
}
}
}
print $folder_list;
print $file_list;
This only loops through everything once, rather than requiring multiple passes.
I have a solution for N deep recursive directory scan:
function scanRecursively($dir = "/") {
$scan = array_diff(scandir($dir), array('.', '..'));
$tree = array();
$queue = array();
foreach ( $scan as $item )
if ( is_file($item) ) $queue[] = $item;
else $tree[] = scanRecursively($dir . '/' . $item);
return array_merge($tree, $queue);
}
Store the output in 2 arrays, then iterate through the arrays to output them in the right order.
$dir = '/master/files';
$contents = scandir($dir);
// create blank arrays to store folders and files
$folders = $files = array();
foreach ($contents as $file) {
if (($file != '.') && ($file != '..')) {
if (is_dir($dir.'/'.$file)) {
// add to folders array
$folders[] = $file;
} else {
// add to files array
$files[] = $file;
}
}
}
// output folders
foreach ($folders as $folder) {
echo '<li class="folder">' . $folder . '</li>';
}
// output files
foreach ($files as $file) {
echo '<li class="file">' . $file . '</li>';
}
Being a CodeIgniter lover, I have in fact modified the core directory_helper from that to include the ability to have certain files exempt from the scanning in addition to setting the depth and choosing if hidden files should be included.
All credit goes to the original authors of CI. I simply added to it
with the exempt array and building in the sorting.
It uses ksort to order the folders, as the folder name is set as the key and natsort to order the files inside each folder.
The only thing you may need to do is define what the DIRECTORY_SEPARATOR is for your environment but I don't think you will need to modify much else.
function directory_map($source_dir, $directory_depth = 0, $hidden = FALSE, $exempt = array())
{
if ($fp = #opendir($source_dir))
{
$folddata = array();
$filedata = array();
$new_depth = $directory_depth - 1;
$source_dir = rtrim($source_dir, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
while (FALSE !== ($file = readdir($fp)))
{
// Remove '.', '..', and hidden files [optional]
if ($file === '.' OR $file === '..' OR ($hidden === FALSE && $file[0] === '.'))
{
continue;
}
is_dir($source_dir.$file) && $file .= DIRECTORY_SEPARATOR;
if (($directory_depth < 1 OR $new_depth > 0) && is_dir($source_dir.$file))
{
$folddata[$file] = directory_map($source_dir.$file, $new_depth, $hidden, $exempt);
}
elseif(empty($exempt) || !empty($exempt) && !in_array($file, $exempt))
{
$filedata[] = $file;
}
}
!empty($folddata) ? ksort($folddata) : false;
!empty($filedata) ? natsort($filedata) : false;
closedir($fp);
return array_merge($folddata, $filedata);
}
return FALSE;
}
Usage example would be:
$filelist = directory_map('full_server_path');
As mentioned above, it will set the folder name as the key for the child array, so you can expect something along the lines of the following:
Array(
[documents/] => Array(
[0] => 'document_a.pdf',
[1] => 'document_b.pdf'
),
[images/] => Array(
[tn/] = Array(
[0] => 'picture_a.jpg',
[1] => 'picture_b.jpg'
),
[0] => 'picture_a.jpg',
[1] => 'picture_b.jpg'
),
[0] => 'file_a.jpg',
[1] => 'file_b.jpg'
);
Just keep in mind that the exempt will be applied to all folders. This is handy if you want to skip out a index.html file or other file that is used in the directories you don't want included.
Try
<?php
$path = $_SERVER['DOCUMENT_ROOT'];
chdir ($path);
$dir = array_diff (scandir ('.'), array ('.', '..', '.DS_Store', 'Thumbs.db'));
usort ($dir, create_function ('$a,$b', '
return is_dir ($a)
? (is_dir ($b) ? strnatcasecmp ($a, $b) : -1)
: (is_dir ($b) ? 1 : (
strcasecmp (pathinfo ($a, PATHINFO_EXTENSION), pathinfo ($b, PATHINFO_EXTENSION)) == 0
? strnatcasecmp ($a, $b)
: strcasecmp (pathinfo ($a, PATHINFO_EXTENSION), pathinfo ($b, PATHINFO_EXTENSION))
))
;
'));
header ('content-type: text/plain');
print_r ($dir);
?>
public function sortedScanDir($dir) {
// scan the current folder
$content = scandir($dir);
// create arrays
$folders = [];
$files = [];
// loop through
foreach ($content as $file) {
$fileName = $dir . '/' . $file;
if (is_dir($fileName)) {
$folders[] = $file;
} else {
$files[] = $file;
}
}
// combine
return array_merge($folders, $files);
}
The code below is part of a function for grabbing 5 image files from a given directory.
At the moment readdir returns the images 'in the order in which they are stored by the filesystem' as per the spec.
My question is, how can I modify it to get the latest 5 images? Either based on the last_modified date or the filename (which look like 0000009-16-5-2009.png, 0000012-17-5-2009.png, etc.).
if ( $handle = opendir($absolute_dir) )
{
$i = 0;
$image_array = array();
while ( count($image_array) < 5 && ( ($file = readdir($handle)) !== false) )
{
if ( $file != "." && $file != ".." && $file != ".svn" && $file != 'img' )
{
$image_array[$i]['url'] = $relative_dir . $file;
$image_array[$i]['last_modified'] = date ("F d Y H:i:s", filemtime($absolute_dir . '/' . $file));
}
$i++;
}
closedir($handle);
}
If you want to do this entirely in PHP, you must find all the files and their last modification times:
$images = array();
foreach (scandir($folder) as $node) {
$nodePath = $folder . DIRECTORY_SEPARATOR . $node;
if (is_dir($nodePath)) continue;
$images[$nodePath] = filemtime($nodePath);
}
arsort($images);
$newest = array_slice($images, 0, 5);
If you are really only interested in pictures you could use glob() instead of soulmerge's scandir:
$images = array();
foreach (glob("*.{png,jpg,jpeg}", GLOB_BRACE) as $filename) {
$images[$filename] = filemtime($filename);
}
arsort($images);
$newest = array_slice($images, 0, 5);
Or you can create function for the latest 5 files in specified folder.
private function getlatestfivefiles() {
$files = array();
foreach (glob("application/reports/*.*", GLOB_BRACE) as $filename) {
$files[$filename] = filemtime($filename);
}
arsort($files);
$newest = array_slice($files, 0, 5);
return $newest;
}
btw im using CI framework. cheers!