How to check if a folder has sub folders using glob? - php

I have a dir TestRoot with two folder: TestFolderA, which has another folder and two files, and TestFolderB which only has one file. I am trying to check whether these folders themselves contain more folders.
<!DOCTYPE html>
<html dir="ltr" lang="en-US">
<head>
</head>
<body class="stretched">
<?php
$root = "docs/RootTest";
$files = scandir($root);
foreach($files as $file)
{
if ($file != '.' && $file != '..')
{
$link = $root.'//'.$file;
if(is_dir($link)) //Check if file is a folder
{
$folders = glob($link."/", GLOB_ONLYDIR);
if(count($folders)>0) //Check if it contains more folders
{
echo $link." ";
echo "Has Sub-folders ";
}
else
{
echo $link." ";
echo "None ";
}
}
}
}
?>
</body>
</html>
When I run this code the output is "docs/RootTest//TestFolderA Has Sub-folders" which is correct however I also get the output "docs/RootTest//TestFolderB Has Sub-folders" which is not correct. What am I doing wrong?

$dirs = array_filter(glob('*'), 'is_dir');
print_r( $dirs);
You can also try glob() followed GLOB_ONLYDIR option

Change line
$folders = glob($link."/", GLOB_ONLYDIR);
to
$folders = glob($link."/*", GLOB_ONLYDIR);
Just added "*"

OK albeit not the way I wanted to, but after glob for some reason refuses to behave as expected I I instead opted to just scan the directory again and sorted it so that folders are first in the array. Then I just checked if the first element is a directory.
if(is_dir($link))
{
$folders = scandir($link, 1);
if(is_dir($link.'/'.$folders[0]))
{
echo $link." ";
echo "Has Sub-folders ";
}

PHP is_dir() Function
The is_dir() function checks whether the specified file is a directory.
This function returns TRUE if the directory exists.
<?php
$file = "images";
if(is_dir($file))
{
echo ("$file is a directory");
}
else
{
echo ("$file is not a directory");
}
?>
Output :
images is a directory

Related

php - listing folders and files in a directory

hi there i am using the following function to list all the files and folders in a directory.
<?php
function listFolderFiles($dir){
$ffs = scandir($dir);
foreach($ffs as $ff){
echo $ff . "<br/>";
}
}
?>
but the problem seems to be i'm getting all the folders in the directory alright but i'm also getting a . and a ... something like the one below.
.
..
direc
img
music
New Text Document.txt
and i am using the following function like: listFolderFiles('MyFolder');
what i want to do is get all the folders and files but not the . and the .., what have i done wrong and how can i get what i want. thanks!
Easy way to get rid of the dots that scandir() picks up in Linux environments:
<?php
$ffs = array_diff(scandir($dir), array('..', '.'));
?>
You can use glob quite easily, which puts the filenames into an array:
print_r(glob("*.*"));
example:
// directory name
$directory = "/";
// get in directory
$files = glob($directory . "*");
$d = 0; // init dir array count
$f = 0; // init file array count
// directories and files
foreach($files as $file) {
if(is_dir($file)) {
array($l['directory'][$d] = $file);
$d++;
} else {
array($l['file'][$f] = $file);
$f++;
}
}
print_r($l);
NOTE: scandir will also pick up hidden files such as .htaccess, etc. That is why the glob method should be considered instead, unless of course you want to show them.
This should do it!
<?php
function listFolderFiles($dir){
$ffs = scandir($dir);
foreach($ffs as &$ff){
if ($ff != '.' && $ff != '..') {
echo $ff . "<br/>";
}
}
}
?>

Get files names inside a directory path

Is there any PHP function to retrieve the file/s name/s inside a directory path?
E.g., I have a CSS file inside /css, and I want to get this file's name.
Solution:
As #ShankarDamodaran suggested, I used:
//Get CSS file/s name/s
chdir($_SERVER['DOCUMENT_ROOT'] . '/css'); //<--- Set the directory here...
foreach (glob("*.css") as $filename) { //<----Get only CSS files
$CSSfiles[] = $filename;
}
This will return an array ($CSSfiles) with the names of the CSS files.
Make use of glob() for this
<?php
chdir('../css'); //<--- Set the directory here...
foreach (glob("*.*") as $filename) { //<--- Pass *.css , (If you need just the CSS files)
echo $filename."<br>";
}
<pre>
<?php
if ($handle = opendir('css')) {
echo "Directory handle: $handle\n";
echo "Entries:\n";
while (false !== ($entry = readdir($handle))) {
echo "$entry\n";
}
}
closedir($handle);
?>
</pre>
USE
<?PHP echo realpath('YOURFILE.PHP');?>
CHECK HERE

php script for generating links to folders

Need help for a php script / page for generating links to folders.
Have a homepage with photos that I upload using Lightroom – each album in a separate folder.
The structure is:
mysite.com
|--images
|--folder1
|--folder2
|--folder3
.
.
So I would like to end up with a dynamic index.php file that generates links to all the subfolders of “images” instead of the static index.html file I got in the root of mysite.com:
<html>
<body>
folder1
folder2
folder3
.
.
</body>
</html>
Thanx in advance
<?php
$files = scandir();
$dirs = array(); // contains all your images folder
foreach ($files as $file) {
if (is_dir($file)) {
$dirs[] = $file;
}
}
?>
use dirs array for dynamically generating links
Maybe something like this:
$dir = "mysite.com/images/";
$dh = opendir($dir);
while ($f = readdir($dh)) {
$fullpath = $dir."/".$f;
if ($f{0} == "." || !is_dir($fullpath)) continue;
echo "$f\n";
}
closedir($dh);
When I need everything (i.e., something/*), I prefer readdir() over glob() because of speed and less memory consumption (reading a directory file by file, instead of getting the whole thing in an array).
If I'm not mistaken, glob() does omit .*files and has no need for the $fullpath variable, so if you're after speed, you might want to do some testing.
Try something like this:
$contents = glob('mysite.com/images/*');
foreach ($contents as content) {
$path = explode('/', $content);
$folder = array_pop($path);
echo '' . $folder . '';
}
Or also this:
if ($handle = opendir('mysite.com/images/') {
while (false !== ($content = readdir($handle))) {
echo echo '' . $content . '';
}
closedir($handle);
}

move all files in a folder to another?

when moving one file from one location to another i use
rename('path/filename', 'newpath/filename');
how do you move all files in a folder to another folder? tried this one without result:
rename('path/*', 'newpath/*');
A slightly verbose solution:
// Get array of all source files
$files = scandir("source");
// Identify directories
$source = "source/";
$destination = "destination/";
// Cycle through all source files
foreach ($files as $file) {
if (in_array($file, array(".",".."))) continue;
// If we copied this successfully, mark it for deletion
if (copy($source.$file, $destination.$file)) {
$delete[] = $source.$file;
}
}
// Delete all successfully-copied files
foreach ($delete as $file) {
unlink($file);
}
Please try this solution, it's tested successfully ::
<?php
$files = scandir("f1");
$oldfolder = "f1/";
$newfolder = "f2/";
foreach($files as $fname) {
if($fname != '.' && $fname != '..') {
rename($oldfolder.$fname, $newfolder.$fname);
}
}
?>
An alternate using rename() and with some error checking:
$srcDir = 'dir1';
$destDir = 'dir2';
if (file_exists($destDir)) {
if (is_dir($destDir)) {
if (is_writable($destDir)) {
if ($handle = opendir($srcDir)) {
while (false !== ($file = readdir($handle))) {
if (is_file($srcDir . '/' . $file)) {
rename($srcDir . '/' . $file, $destDir . '/' . $file);
}
}
closedir($handle);
} else {
echo "$srcDir could not be opened.\n";
}
} else {
echo "$destDir is not writable!\n";
}
} else {
echo "$destDir is not a directory!\n";
}
} else {
echo "$destDir does not exist\n";
}
tried this one?:
<?php
$oldfolderpath = "old/folder";
$newfolderpath = "new/folder";
rename($oldfolderpath,$newfolderpath);
?>
So I tried to use the rename() function as described and I kept getting the error back that there was no such file or directory. I placed the code within an if else statement in order to ensure that I really did have the directories created. It looked like this:
$tempDir = '/home/site/images/tmp/';
$permanentDir = '/home/site/images/' . $claimid; // this was stored above
mkdir($permanentDir,0775);
if(is_dir($permanentDir)){
echo $permanentDir . ' is a directory';
if(is_dir($tempDir)){
echo $tempDir . ' is a directory';
}else{
echo $tempDir . ' is not a directory';
}
}else{
echo $permanentDir . ' is not a directory';
}
rename($tempDir . "*", $permanentDir);
So when I ran the code again, it spit out that both paths were directories. I was stumped. I talked with a coworker and he suggested, "Why not just rename the temp directory to the new directory, since you want to move all the files anyway?"
Turns out, this is what I ended up doing. I gave up trying to use the wildcard with the rename() function and instead just use the rename() to rename the temp directory to the permanent one.
so it looks like this.
$tempDir = '/home/site/images/tmp/';
$permanentDir = '/home/site/images/' . $claimid; // this was stored above
mkdir($permanentDir,0775);
rename($tempDir, $permanentDir);
This worked beautifully for my purposes since I don't need the old tmp directory to remain there after the files have been uploaded and "moved".
Hope this helps. If anyone knows why the wildcard doesn't work in the rename() function and why I was getting the error stating above, please, let me know.
Move or copy the way I use it
function copyfiles($source_folder, $target_folder, $move=false) {
$source_folder=trim($source_folder, '/').'/';
$target_folder=trim($target_folder, '/').'/';
$files = scandir($source_folder);
foreach($files as $file) {
if($file != '.' && $file != '..') {
if ($move) {
rename($source_folder.$file, $target_folder.$file);
} else {
copy($source_folder.$file, $target_folder.$file);
}
}
}
}
function movefiles($source_folder, $target_folder) {
copyfiles($source_folder, $target_folder, $move=true);
}
try this:
rename('path/*', 'newpath/');
I do not see a point in having an asterisk in the destination
If the target directory doesn't exist, you'll need to create it first:
mkdir('newpath');
rename('path/*', 'newpath/');
As a side note; when you copy files to another folder, their last changed time becomes current timestamp. So you should touch() the new files.
... (some codes for directory looping) ...
if (copy($source.$file, $destination.$file)) {
$delete[] = $source.$file;
$filetimestamp = filemtime($source.$file);
touch($destination.$file,$filetimestamp);
}
... (some codes) ...
Not sure if this helps anyone or not, but thought I'd post anyway. Had a challenge where I has heaps of movies I'd purchased and downloaded through various online stores all stored in one folder, but all in their own subfolders and all with different naming conventions. I wanted to move all of them into the parent folder and rename them all to look pretty. all of the subfolders I'd managed to rename with a bulk renaming tool and conditional name formatting. the subfolders had other files in them i didn't want. so i wrote the following php script to, 1. rename/move all files with extension mp4 to their parent directory while giving them the same name as their containing folder, 2. delete contents of subfolders and look for directories inside them to empty and then rmdir, 3. rmdir the subfolders.
$handle = opendir("D:/Movies/");
while ($file = readdir($handle)) {
if ($file != "." && $file != ".." && is_dir($file)) {
$newhandle = opendir("D:/Movies/".$file);
while($newfile = readdir($newhandle)) {
if ($newfile != "." && $newfile != ".." && is_file("D:/Movies/".$file."/".$newfile)) {
$parts = explode(".",$newfile);
if (end($parts) == "mp4") {
if (!file_exists("D:/Movies/".$file.".mp4")) {
rename("D:/Movies/".$file."/".$newfile,"D:/Movies/".$file.".mp4");
}
else {
unlink("D:/Movies/".$file."/".$newfile);
}
}
else { unlink("D:/Movies/".$file."/".$newfile); }
}
else if ($newfile != "." && $newfile != ".." && is_dir("D:/Movies/".$file."/".$newfile)) {
$dirhandle = opendir("D:/Movies/".$file."/".$newfile);
while ($dirfile = readdir($dirhandle)){
if ($dirfile != "." && $dirfile != ".."){
unlink("D:/Movies/".$file."/".$newfile."/".$dirfile);
}
}
rmdir("D:/Movies/".$file."/".$newfile);
}
}
unlink("D:/Movies/".$file);
}
}
i move all my .json files from root folder to json folder with this
foreach (glob("*.json") as $filename) {
rename($filename,"json/".$filename);
}
pd: someone 2020?

PHP Directory Listing Code Malfunction

I tried to write a script to list all files in directories and subdirectories and so on.. The script works fine if I don't include the check to see whether any of the files are directories. The code doesn't generate errors but it generates a hundred lines of text saying "Directory Listing of ." instead of what I was expecting. Any idea why this isn't working?
<?php
//define the path as relative
$path = "./";
function listagain($pth)
{
//using the opendir function
$dir_handle = #opendir($pth) or die("Unable to open $pth");
echo "Directory Listing of $pth<br/>";
//running the while loop
while ($file = readdir($dir_handle))
{
//check whether file is directory
if(is_dir($file))
{
//if it is, generate it's list of files
listagain($file);
}
else
{
if($file!="." && $file!="..")
echo "<a href='$file'>$file</a><br/>";
}
}
//closing the directory
closedir($dir_handle);
}
listagain($path)
?>
The first enties . and .. refer to the current and parent directory respectivly. So you get a infinite recursion.
You should first check for that before checking the file type:
if ($file!="." && $file!="..") {
if (is_dir($file)) {
listagain($file);
} else {
echo ''.htmlspecialchars($file).'<br/>';
}
}
The problem is, variable $file contains only basename of path. So, you need to use $pth.$file.

Categories