Delete set of directories - php

I would like to delete set of directories but 1st I'm gonna have to get the directories names so suppose I've the following site www.my_site.com and would use the following code to get all directories names.
$get_dirs = glob("*", GLOB_ONLYDIR);
for ($i=0;$i<count($get_dirs);$i++){
echo $get_dirs[$i].'+'; // Will show results divided by + sign
}
suppose the results as following (if I've 5 directories and note it divided by + sign)
dir1+dir2+dir3+dir4+dir5+
to use it
rrmdir(dir1); // that would delete only directory dir1
My Question
How to explode the results of directories names dir1+dir2+dir3+dir4+dir5+ based on the + sign and loop using delete function on all so finally all directories dir1 and dir2 and dir3 and dir4 and dir5 are deleted.

I think this is what your trying to do?
$dir = trim('dir1+dir2+dir3+dir4+dir5+', '+');
$arr = explode("+", $dir);
foreach ($arr as $a){
rrmdir($a);
}
You have a extra '+' at the end, so trim($val ,'+')

You answered Your own question there actually:
$dirs = explode('+', $get_dirs);
foreach ($dirs as $dir) {
rrmdir($dir);
}
or did i understand something wrong? And why don't you do it already in for cycle?

Related

PHP If-Else does not work for comparing filecontents

I am trying to make a PHP application which searches through the files of your current directory and looks for a file in every subdirectory called email.txt, then it gets the contents of the file and compares the contents from email.txt with the given query and echoes all the matching directories with the given query. But it does not work and it looks like the problem is in the if-else part of the script at the end because it doesn't give any output.
<?php
// pulling query from link
$query = $_GET["q"];
echo($query);
echo("<br>");
// listing all files in doc directory
$files = scandir(".");
// searching trough array for unwanted files
$downloader = array_search("downloader.php", $files);
$viewer = array_search("viewer.php", $files);
$search = array_search("search.php", $files);
$editor = array_search("editor.php", $files);
$index = array_search("index.php", $files);
$error_log = array_search("error_log", $files);
$images = array_search("images", $files);
$parsedown = array_search("Parsedown.php", $files);
// deleting unwanted files from array
unset($files[$downloader]);
unset($files[$viewer]);
unset($files[$search]);
unset($files[$editor]);
unset($files[$index]);
unset($files[$error_log]);
unset($files[$images]);
unset($files[$parsedown]);
// counting folders
$folderamount = count($files);
// defining loop variables
$loopnum = 0;
// loop
while ($loopnum <= $folderamount + 10) {
$loopnum = $loopnum + 1;
// gets the emails from every folder
$dirname = $files[$loopnum];
$email = file_get_contents("$dirname/email.txt");
//checks if the email matches
if ($stremail == $query) {
echo($dirname);
}
}
//print_r($files);
//echo("<br><br>");
?>
Can someone explain / fix this for me? I literally have no clue what it is and I debugged soo much already. It would be heavily gracious and appreciated.
Kind regards,
Bluppie05
There's a few problems with this code that would be preventing you from getting the correct output.
The main reason you don't get any output from the if test is the condition is (presumably) using the wrong variable name.
// variable with the file data is called $email
$email = file_get_contents("$dirname/email.txt");
// test is checking $stremail which is never given a value
if ($stremail == $query) {
echo($dirname);
}
There is also an issue with your scandir() and unset() combination. As you've discovered scandir() basically gives you everything that a dir or ls would on the command line. Using unset() to remove specific files is problematic because you have to maintain a hardcoded list of files. However, unset() also leaves holes in your array, the count changes but the original indices do not. This may be why you are using $folderamount + 10 in your loop. Take a look at this Stack Overflow question for more discussion of the problem.
Rebase array keys after unsetting elements
I recommend you read the PHP manual page on the glob() function as it will greatly simplify getting the contents of a directory. In particular take a look at the GLOB_ONLYDIR flag.
https://www.php.net/manual/en/function.glob.php
Lastly, don't increment your loop counter at the beginning of the loop when using the counter to read elements from an array. Take a look at the PHP manual page for foreach loops for a neater way to iterate over an array.
https://www.php.net/manual/en/control-structures.foreach.php

How to calculate files in a particular folder based on file name in PHP

I want to build a program for a photo studio that will calculate files in a folder for example I have a folder named Upload and it contains 10 files
7 of the files are named 1 5x7 and
3 of the files are named 2 5x7.
I want the program that will sum them up based on the first letter of the file name.
All I was able the do is to scan the directory and list the files in this directory.
<?php $dir = "/upload/"; $list = scandir($dir); print_r($list);?>
Any help will be greatly appreciated.
Unless I'm misunderstanding your requirements, this might do it ...
$files = scandir('/upload/');
$counts = [];
foreach ($files as $f) {
$char1 = substr($f,0,1);
$counts[$char1] = empty($counts[$char1]) ? 1 : $counts[$char1]+1;
}

Listing of folders/subfolders with RecursiveDirectoryIterator

I'm using this code to get a listing of every folders/subfolders of a repertory :
$path = realpath($userdir);
foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($path)) as $filename)
{
echo "$filename\n";
}
However it displays something like this, wich add dot or double dots and displays the folder twice :
C:\wamp\www\gg\ftp\repository\user\mister.
C:\wamp\www\gg\ftp\repository\user\mister..
C:\wamp\www\gg\ftp\repository\user\mister\apatik.
C:\wamp\www\gg\ftp\repository\user\mister\apatik..
C:\wamp\www\gg\ftp\repository\user\mister\vvxcv.
C:\wamp\www\gg\ftp\repository\user\mister\vvxcv..
C:\wamp\www\gg\ftp\repository\user\mister\vvxcv\vcxvcx.
C:\wamp\www\gg\ftp\repository\user\mister\vvxcv\vcxvcx..
Instead of something cleaner like this :
C:\wamp\www\gg\ftp\repository\user\mister
C:\wamp\www\gg\ftp\repository\user\mister\apatik
C:\wamp\www\gg\ftp\repository\user\mister\vvxcv
C:\wamp\www\gg\ftp\repository\user\mister\vvxcv\vcxvcx
Is there a way ? I was previously using the function glob
glob($sub . '/*' , GLOB_ONLYDIR);
which was displaying the folder correctly but i couldn't get it to be recursive to display subfolders aswell.
Thanks
you need something like this
set_time_limit(0);
function scanDirectory($sub = ''){
$folders = glob($sub . '/*' , GLOB_ONLYDIR);
foreach($folders as $folder){
echo "$folder<br />";
scanDirectory($folder);
}
}
scanDirectory();
and this will list all folders on current drive
EDIT
$folders = glob($sub . '/*' , GLOB_ONLYDIR); will get all the folders in specified directory.
foreach($folders as $folder) will loop over folders array.
$sub will be the folder name that will be explored.
so, these are the folders
A B C
$folders will have like $folders['A', 'B', 'C']
and in loop, each A B and C will be passed as $sub to check either it has more folders in it or not.

Wrong result of sizeof

I have several files in a folder and i want to count them.
$folder = "images";
$allPics = scandir($folder);
$result = sizeof($allPics);
echo $result;
The result is 350 but it should be 348. I don't get it why it is showing me the result +2?
Am i missing something?!
http://php.net/manual/en/function.scandir.php
When looking at the documentation you can see the function return both '.' and '..', that's why you're having 2 more than you should have.
You can use this:
array_diff(scandir($folder), array('..', '.'));
To get rid of the dots you don't wanna have.
You are using the unix system and it have, 2 pointers in each directory, the pointer for the parent dirrectory that usualy is notted with .. and the pointer to the current directory that is notted as .

PHP: Most efficient way to get the number of files within a directory

Consider these two folder structures:
Foo/
Folder1/
File1.txt
Folder2/
Folder3/
File2.txt
Bar/
Folder1/
Folder2/
Folder3/
Folder4/
I'd like to know the most efficient way in PHP to tell me that the "Foo" folder has two files in it and that the "Bar" folder has zero files in it. Notice that it's recursive. Even though the "File1.txt" file is not immediately inside the "Foo" folder, I still want it to count. Also, I don't care what the names of the files are. I just want the total number of files.
Any help would be appreciated. Thanks!
Use RecursiveDirectoryIterator. Here is the documentation.
$rdi = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('/home/thrustmaster/Temp', FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::LEAVES_ONLY);
foreach ($rdi as $file)
echo "$file\n";
print iterator_count($rdi);
You need a recursive function to loop through the directory structure. That's all you can really do to count the number of files without going with object orientated solution.
This function will recursively count the number of files in a directory and it's sub-directories.
function countDir($dir, $i = 0) {
if ($handle = opendir($dir.'/')) {
while (false !== ($file = readdir($handle))) {
// Check for hidden files the array[0] on a
// string returns the first character
if ($file[0] != '.') {
if (is_dir($dir.'/'.$file)) {
$i += countDir($dir.$file, $i);
} else {
$i++;
}
}
}
}
return $i;
}

Categories