how to delete a folder which is empty using PHP - php

<?php
function rmdirr($dirname){
// Sanity check
$dirname = "TEST/";
if (!file_exists($dirname)) {
return false;
}
// Simple delete for a file
if (is_file($dirname)) {
return unlink($dirname);
}
// Loop through the folder
$dir = dir($dirname);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == "." || $entry == "..") {
continue;
}
// Recurse
unlink("$dirname/$entry");
}
// Clean up
$dir->close();
return rmdir($dirname);
}
if (rmdirr($_GET['map'])){
echo "TEST FERo";
}
else{
echo "something went wrong.";
}
?>
Its working well and good. But if i need to delete the folder which contains some files and empty folder. In this case it delete all the files but not the empty folder. It throws an exception like…
Warning: unlink(TEST//New Folder) [function.unlink]: Permission denied
in E:\Xampp\xampp\htdocs\delete_FILE\delete_FILE.php on line 23
Warning: rmdir(TEST/) [function.rmdir]: Directory not empty in
E:\Xampp\xampp\htdocs\delete_FILE\delete_FILE.php on line 28
What is the possible way to delete even the folder is empty.

Just use your rmdirr function recursively in the while loop instead of unlink;
function rmdirr($dirname){
// Sanity check
if (!file_exists($dirname)) { return false; }
// Simple delete for a file
if (is_file($dirname)) { return unlink($dirname); }
// Loop through the folder
$dir = dir($dirname);
while (false !== $entry = $dir->read()) {
// Skip pointers
if ($entry == "." || $entry == "..") { continue; }
// Recurse
rmdirr("$dirname/$entry");
}
// Clean up
$dir->close();
return rmdir($dirname);
}
This way it'll also take care of non-empty subfolders...

you have to make sure your webserver is able to delete those files. check the permissions.

You are deleting the files in 1 level only. Your code tries to delete the folder TEST//New Folder using unlink instead of rmdir. You have to check if it's a folder or not, then rmdir or unlink it.

Related

unable to delete a last file in folder while deleting folder using php

I am calling my php function from some other website which delete a folder on my server in background.
This is a function which I am using to delete a folder.
public static function remove($dir)
{
if (is_dir($dir)) {
$diropen = opendir($dir);
while($d = readdir($diropen)) {
if ($d!= '.' && $d != '..') {
self::remove($dir . "/$d");
}
}
#rmdir($dir);
} elseif (is_file($dir)) {
#unlink($dir);
}
}
If I am having three files in folder then it deletes only two and unable to delete last file or unlink fails on last file.
If I am having two files then it deletes only one file.
I have checked writable permission using is_writable it is true for all files.
Can somebody please help me out. or how to debug this behavior as this function is getting called in background.
my directory was open in some other function , so I closedir my folder and then above function working fine.
<?php
function delete_directory($target) {
if (is_dir($target))
$dir_handle = opendir($target);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
else
delete_directory($target.'/'.$file);
}
}
closedir($dir_handle);
rmdir($target);
return true;
}
?>
use closedir and you'll be fine.

Deleting a 340 mode directories

I once used this wrong PHP script which created a 340 mode directories:
<?php
$uname = "secret";
mkdir("/home/u251526215/public_html/user/profile/".$uname."", 755);
?>
The script above creates a 340 CHMOD directories. I've repaired the "755" to "0755" and it is now working perfectly. But for now, how can I delete the 340 directories which were already created? I have tried to delete them using FTP manager, but it kept saying error. I've tried to use rmdir() but it says directory not empty but it is completely empty!
Updated: All action to the directory; rename, move, copy, change permission and open are error returned
Maybe there is a hidden file. I found this function to delete a directory with all contents:
function delete_directory($dirname) {
if (is_dir($dirname))
$dir_handle = opendir($dirname);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirname."/".$file))
unlink($dirname."/".$file);
else
delete_directory($dirname.'/'.$file);
}
}
closedir($dir_handle);
rmdir($dirname);
return true;
}
Source http://www.ozzu.com/programming-forum/php-delete-directory-folder-t47492.html

php ftp check if folder exists always return error creating folder

can someone please tell me what I'm doing wrong in this code?
if($id != '') {
if(is_dir("../public_html".$tem_pasta['path']."/pics/".$id)) {
echo "pasta já existia";
$destination_file = "../public_html".$tem_pasta['path']."/pics/".$id."/".$myFileName;
} else {
//pasta nao existia
if (ftp_mkdir($conn_id, "../public_html".$tem_pasta['path']."/pics/".$id)) {
$destination_file = "../public_html".$tem_pasta['path']."/pics/".$id."/".$myFileName;
//echo "pasta criada<br>";
} else {
echo "erro, não criou a pasta<br>";
}
}
} else {
$destination_file = "../public_html".$tem_pasta['path']."/pics/".$myFileName;
}
it checks if I've a folder ($id) within my pics directory, and if not the script creates a new one.
works good, but if I try to upload another file to the previous created folder it does return an error, saying it didn't create the folder...
thanks
I don't think you can use is_dir on a FTP resource, what you should do is check if the size of the dir/file is -1 with ftp_size.
Because I think what now happens is: you are trying to make the same folder again, and this is why a error occurs.
Edit:
Or check with ftp_chdir!
<?php
function ftp_directory_exists($ftp, $dir)
{
// Get the current working directory
$origin = ftp_pwd($ftp);
// Attempt to change directory, suppress errors
if (#ftp_chdir($ftp, $dir))
{
// If the directory exists, set back to origin
ftp_chdir($ftp, $origin);
return true;
}
// Directory does not exist
return false;
}
?>
Should work!
is_dir works only on the local file-system. If you want to check if a ftp-directory already exists try this:
function ftp_is_dir($ftp, $dir)
{
$pushd = ftp_pwd($ftp);
if ($pushd !== false && #ftp_chdir($ftp, $dir))
{
ftp_chdir($ftp, $pushd);
return true;
}
return false;
}
if($id != '') {
if(ftp_is_dir($conn_id, "../public_html".$tem_pasta['path']."/pics/".$id)) {
// and so on...
Use ftp_nlist and in_array
$ftp_files = #ftp_nlist($this->connection, $directory);
if ($ftp_files === false) {
throw new Exception('Unable to list files. Check directory exists: ' . $directory);
}
if (!in_array($directory, $ftp_files)) {
$ftp_mkdir = #ftp_mkdir($this->connection, $directory);
if ($ftp_mkdir === false) {
throw new Exception('Unable to create directory: ' . $directory);
}
}
With PHP 8.0 (on AWS) the solution with #ftp_chdir() does not hide the error and causes the program to stop. The solution with ftp_nlist() doesn't give good results because it returns either false if the path doesn't exist or an element if the path is a file or a list if it's a directory but doesn't give the "." and ".." elements that would identify a directory.
The ftp_mlsd() function seemed more convenient: it returns a list, possibly empty, only if the path is a directory, false otherwise. But it doesn't work correctly on all servers!
Finally it is the ftp_rawlist() function which seems to be the most generalized because it launches a LIST command on the server and returns the result. If the path is a directory we have an array, possibly empty and we have the value false if it is not a directory.
$list = ftp_rawlist( $ftp_conn, $remote_path );
$is_dir = is_array( $list );

How do I set the permissions of the files I extract with ezcArchive - ezComponents

I am using the ezcomponents archive component to extract uploaded files that is being uploaded to my website. The extracting part is very easy but how do I specifically assign the right permissions to those files being extracted?
http://ezcomponents.org/docs/tutorials/Archive#usage
$extract_dir = 'some existing directory';
$archive = ezcArchive::open($file, ezcArchive::ZIP);
while( $archive->valid() )
{
if ( is_dir($extract_dir) === false )
{
#mkdir($extract_dir, 0777);
}
// Extract the current archive entry to /data/<issue_id>/
$archive->extractCurrent($extract_dir);
$archive->next();
}
Regards
You can use a callback for every extracted file/directory, in order to set the desired permissions. You specify the callback through the ezcArchiveOptions.
Do a recursive chmod on the directory. (Use this, if you don't find a built in functionality in ezcomponents)
<?php
function chmodr($path, $filemode) {
if (!is_dir($path))
return chmod($path, $filemode);
$dh = opendir($path);
while (($file = readdir($dh)) !== false) {
if($file != '.' && $file != '..') {
$fullpath = $path.'/'.$file;
if(is_link($fullpath))
return FALSE;
elseif(!is_dir($fullpath) && !chmod($fullpath, $filemode))
return FALSE;
elseif(!chmodr($fullpath, $filemode))
return FALSE;
}
}
closedir($dh);
if(chmod($path, $filemode))
return TRUE;
else
return FALSE;
}
?>

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?

Categories