I'm using php to delete folders containing images of posts that where deleted. I'm using the code below which I found online and does a good job.
I want to know how can I delete only a specific folder in a folder when there are other folders in it.
When I using the code below, how is it possible to do this?
Using: /dev/images/norman/8 -> Will not delete folder 8
Using: /dev/images/norman/ -> Will delete all folders
Eg:
/dev/images/norman/8 -> I need to delete only this folder
/dev/images/norman/9
/dev/images/norman/10
/dev/images/norman/11
/dev/images/norman/12
<?php
$path = $_SERVER['DOCUMENT_ROOT'].'/dev/images/norman/8';
emptyDir($path);
function emptyDir($path) {
// INITIALIZE THE DEBUG STRING
$debugStr = '';
$debugStr .= "Deleting Contents Of: $path<br /><br />";
// PARSE THE FOLDER
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
// IF IT"S A FILE THEN DELETE IT
if(is_file($path."/".$file)) {
if(unlink($path."/".$file)) {
$debugStr .= "Deleted File: ".$file."<br />";
}
} else {
// IT IS A DIRECTORY
// CRAWL THROUGH THE DIRECTORY AND DELETE IT'S CONTENTS
if($handle2 = opendir($path."/".$file)) {
while (false !== ($file2 = readdir($handle2))) {
if ($file2 != "." && $file2 != "..") {
if(unlink($path."/".$file."/".$file2)) {
$debugStr .= "Deleted File: $file/$file2<br />";
}
}
}
}
if(rmdir($path."/".$file)) {
$debugStr .= "Directory: ".$file."<br />";
}
}
}
}
}
echo $debugStr;
}
?>
<?php
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;
}
?>
if you are using, version 5.1 and above,
<?php
function deleteDir($dir) {
$iterator = new RecursiveDirectoryIterator($dir);
foreach (new RecursiveIteratorIterator($iterator, RecursiveIteratorIterator::CHILD_FIRST) as $file)
{
if ($file->isDir()) {
rmdir($file->getPathname());
} else {
unlink($file->getPathname());
}
}
rmdir($dir);
}
deleteDir("temporary");
?>
You want to hear about rmdir.
if(is_file($path."/".$file)) {
if(unlink($path."/".$file)) {
$debugStr .= "Deleted File: ".$file."<br />";
}
} else {
if(rmdir($path."/".$file)) {
$debugStr .= "Deleted Directory: ".$file."<br />";
}
}
EDIT: as rmdir can only handle empty dirs, you may use this solution as reported in rmdir's page comments:
function rrmdir($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file))
rrmdir($file);
else
unlink($file);
}
rmdir($dir);
}
It just recursively deletes everything in $dir, then gets rid of directory itself.
I added an $exclude param to your function, this param it's an array with the names of directories you want to exclude from being deleted, like so:
$path = $_SERVER['DOCUMENT_ROOT'].'/dev/images/norman/';
emptyDir($path); //will delete all under /norman/
emptyDir($path, array('8')); //will delete all under /norman/ except dir 8
emptyDir($path, array('8','10')); //will delete all under /norman/ except dir 8 and 10
function emptyDir($path,$exclude=false) {
// INITIALIZE THE DEBUG STRING
$debugStr = '';
$debugStr .= "Deleting Contents Of: $path<br /><br />";
if (!$exclude) {
$exclude = array();
}
// PARSE THE FOLDER
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
// IF IT"S A FILE THEN DELETE IT
if(is_file($path."/".$file)) {
if(unlink($path."/".$file)) {
$debugStr .= "Deleted File: ".$file."<br />";
}
} else if (!in_array($file, $exclude)) {
// IT IS A DIRECTORY
// CRAWL THROUGH THE DIRECTORY AND DELETE IT'S CONTENTS
if($handle2 = opendir($path."/".$file)) {
while (false !== ($file2 = readdir($handle2))) {
if ($file2 != "." && $file2 != "..") {
if(unlink($path."/".$file."/".$file2)) {
$debugStr .= "Deleted File: $file/$file2<br />";
}
}
}
}
if(rmdir($path."/".$file)) {
$debugStr .= "Directory: ".$file."<br />";
}
}
}
}
}
echo $debugStr;
}
You can use system commands ex. exec("rm -rf {$dirPath}"); or if you want to do it by PHP you have to go recursive, loops won't do it right.
public function deleteDir($path) {
if ($handle = opendir($path)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") {
// IF IT"S A FILE THEN DELETE IT
if(is_file($path."/".$file)) {
if(unlink($path."/".$file)) {
$debugStr .= "Deleted File: ".$file."<br />";
}
} else {
deleteDir($path."/".$file."/");
rmdir($path."/".$file);
}
}
}
}
}
When I using the code below, how is it possible to do this? Using:
/dev/images/norman/8 -> Will not delete folder 8 Using:
/dev/images/norman/ -> Will delete all folders
I think your problem is that you're missing "/" at the end of "/dev/images/norman/8"
$path='./ggg';
rrmdir($path);
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
Related
So I'm creating an image upload site and I need to delete multiple directories and files simultaneously. I have managed to create code that does the job however I'm unsure whether this is 'good code' as I'm repeating myself.
Is there a better way to write the below?
$dirname = 'uploads/'.$album_id;
$dirnamethumb = 'uploads/thumbs/'.$album_id;
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);
}
}
if (is_dir($dirnamethumb))
$dir_handle = opendir($dirnamethumb);
if (!$dir_handle)
return false;
while($file = readdir($dir_handle)) {
if ($file != "." && $file != "..") {
if (!is_dir($dirnamethumb."/".$file))
unlink($dirnamethumb."/".$file);
else
delete_directory($dirnamethumb.'/'.$file);
}
}
closedir($dir_handle);
rmdir($dirname);
rmdir($dirnamethumb);
return true;
Thank you in advance for your help!
Why not try this recursive function from similar question
function rrmdir($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file))
rrmdir($file);
else
unlink($file);
} rmdir($dir);
}
try this,
$dir = '/path/to/some/dir/'; // notice: trailing slash!
if ($handle = opendir($dir)) {
while (false !== ($entry = readdir($handle))) {
if (is_dir($dir . $entry) ) {
rmdir($dir . $entry);
}
}
closedir($handle);
}
?>
i want to list all directory, sub-directory and files using php.
i have tried following code. it returns all the directory, sub directory and files but it's not showing in correct order.
for ex:default order is 1dir, 2dir, 7dir, 8dir while in browser it shows 1dir, 8dir, 7dir, 2dir which is not correct.
code:
function createDir($path = '.')
{
if ($handle = opendir($path))
{
echo "<ul>";
while (false !== ($file = readdir($handle)))
{
if (is_dir($path.$file) && $file != '.' && $file !='..') {
printSubDir($file, $path);
}
else if ($file != '.' && $file !='..'){
$allowed = array('pdf','doc','docx','xls','xlsx','jpg','png','gif','mp4','avi','3gp','flv','mov','PDF','DOC','DOCX','XLS','XLSX','JPG','PNG','GIF','MP4','AVI','3GP','FLV','MOV','html','HTML','css','CSS','js','JS');
$ext = pathinfo($file, PATHINFO_EXTENSION);
if(in_array($ext,$allowed) ) {
$queue[] = $file;
}
}
}
printQueue($queue, $path);
echo "</ul>";
}
}
function printQueue($queue, $path)
{
sort($queue);
foreach ($queue as $file)
{
//printFile($file, $path);
}
}
function printFile($file, $path) {
echo "<li><a href=\"".$path.$file."\" target='_blank'>$file</a></li>";
}
function printSubDir($dir, $path)
{
echo "<li><span class=\"toggle\">$dir</span>";
createDir($path.$dir."/");
echo "</li>";
}
createDir($path);
?>
need help to fix the code and display the direcotry , subdirectory and files in correct order.
I'm having the same problem during listing a directory files. But I have used DirectoryLister
This code is very useful. You can list out your files easily.
You can implement it by following steps.
Download and extract Directory Lister
Copy resources/default.config.php to resources/config.php
Upload index.php and the resources folder to the folder you want listed
Upload additional files to the same directory as index.php
I hope this might help you
You can start by looping the array and printing each directory:
public function dirtree($dir, $regex='', $ignoreEmpty=false) {
if (!$dir instanceof DirectoryIterator) {
$dir = new DirectoryIterator((string)$dir);
}
$dirs = array();
$files = array();
foreach ($dir as $node) {
if ($node->isDir() && !$node->isDot()) {
// print_r($node);
$tree = dirtree($node->getPathname(), $ignoreEmpty);
// print"<pre>";print_r($tree);
if (!$ignoreEmpty || count($tree)) {
$dirs[$node->getFilename()] = $tree;
}
} elseif ($node->isFile()) {
$name = $node->getFilename();
//if ('' == $regex || preg_match($regex, $name)) {
$files[] = $name;
}
}
asort($dirs);
sort($files);
return array_merge($files, $dirs);
}
Use like this:
$fileslist = dirtree('root');
echo "<pre style='font-size:15px'>";
print_r($fileslist);
This question already has answers here:
Delete directory with files in it?
(34 answers)
Closed 5 years ago.
I need a script which can remove a whole directory with all their subfolders, files and etc. I tried with this function which I found in internet before few months ago but it not work completely.
function deleteFile($dir) {
if(substr($dir, strlen($dir)-1, 1) != '/') {
$dir .= '/';
}
if($handle = opendir($dir)) {
while($obj = readdir($handle)) {
if($obj != '.' && $obj != '..') {
if(is_dir($dir.$obj)) {
if(!deleteFile($dir.$obj)) {
echo $dir.$obj."<br />";
return false;
}
}
elseif(is_file($dir.$obj)) {
if(!unlink($dir.$obj)) {
echo $dir.$obj."<br />";
return false;
}
}
}
}
closedir($handle);
if(!#rmdir($dir)) {
echo $dir.'<br />';
return false;
}
return true;
}
return true;
}
For the test I use a unpacked archive of prestashop and I try to delete the folder where archive is unpacked but it doesn't work.
/home/***/public_html/prestashop/img/p/3/
/home/***/public_html/prestashop/img/p/3
/home/***/public_html/prestashop/img/p
/home/***/public_html/prestashop/img
These are the problem folders. At the first time I think - "May is a problem with the chmod of the files" but when I test with all files chmod permission 755 (after that with 777) - the result was the same.
<?php
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir")
rrmdir($dir."/".$object);
else unlink ($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
?>
Try out the above code from php.net
Worked fine for me
function delete_files($dir) {
foreach(glob($dir . '/*') as $file) {
if(is_dir($file)) delete_files($file); else unlink($file);
} rmdir($dir);
}
You can use a cleaner method for doing a recursive delete of a directory.
Example:
function recursiveRemove($dir) {
$structure = glob(rtrim($dir, "/").'/*');
if (is_array($structure)) {
foreach($structure as $file) {
if (is_dir($file)) recursiveRemove($file);
elseif (is_file($file)) unlink($file);
}
}
rmdir($dir);
}
Usage:
recursiveRemove("test/dir/");
The easiest and the best way using the system() method
$dir = dirname ( "/log" );
if ($handle = opendir($dir)) {
while (( $file = readdir($handle)) !== false ) {
if ($file != "." && $file != "..") {
system("rm -rf ".escapeshellarg($dir.'/'.$file));
}
}
}
closedir($handle);
/**
* Deletes a directory and all files and folders under it
* #return Null
* #param $dir String Directory Path
*/
function rmdir_files($dir) {
$dh = opendir($dir);
if ($dh) {
while($file = readdir($dh)) {
if (!in_array($file, array('.', '..'))) {
if (is_file($dir.$file)) {
unlink($dir.$file);
}
else if (is_dir($dir.$file)) {
rmdir_files($dir.$file);
}
}
}
rmdir($dir);
}
}
rmdir("./uploads/temp/".$user."/");
I have many files in a directory I wish to remove in my PHP script, however these is no way for me to unlink() the file first. Is there a way I co do
unlink(* FROM (dir=)) // don't downvote the long shot
// delete all files from the dir first
// then delete that dir
Reference a directory has to be empty in order to delete it, see php.net/manual/en/function.rmdir.php
You can use the DirectoryIterator and unlink together.
use this
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;
}
This code can easily be improved upon, as it's a quick hack, but it takes a directory as an argument and then uses functional recursion to delete all files and folders within, and then finally removes the directory. Nice and quick, too.
There is no other way except to delete all files first using one way or another and then remove directory.
public static function deleteDir($dirPath) {
if (! is_dir($dirPath)) {
throw new InvalidArgumentException('$dirPath must be a directory');
}
if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
$dirPath .= '/';
}
$files = glob($dirPath . '*', GLOB_MARK);
foreach ($files as $file) {
if (is_dir($file)) {
self::deleteDir($file);
} else {
unlink($file);
}
}
rmdir($dirPath);
}
Try using glob to loop over the files in the directory to delete
foreach (glob('/path/to/directory/*') as $file){
unlink('/path/to/directory/' . $file);
}
Check this http://lixlpixel.org/recursive_function/php/recursive_directory_delete/
function recursive_remove_directory($directory, $empty=FALSE)
{
if(substr($directory,-1) == '/')
{
$directory = substr($directory,0,-1);
}
if(!file_exists($directory) || !is_dir($directory))
{
return FALSE;
}elseif(is_readable($directory))
{
$handle = opendir($directory);
while (FALSE !== ($item = readdir($handle)))
{
if($item != '.' && $item != '..')
{
$path = $directory.'/'.$item;
if(is_dir($path))
{
recursive_remove_directory($path);
}else{
unlink($path);
}
}
}
closedir($handle);
if($empty == FALSE)
{
if(!rmdir($directory))
{
return FALSE;
}
}
}
return TRUE;
}
You can delete it recursively:
public function delete_folder ($path) {
$handle = opendir($path);
while ($file = readdir($handle)) {
if ($file != '..' && $file != '.') {
if (is_file($path . DS . $file))
unlink($path . DS . $file);
else
delete_folder($path . DS . $file);
}
}
closedir($handle);
rmdir($tmp_path);
}
delete_folder('path/to/folder');
how can i delete multiple files from the folder?
code:$query=$this->main_model->get($id);
if($query->num_rows()>0)
{
foreach ($query->result() as $row)
{
unlink("uploads/".$id."/".$row->img_name);
unlink("uploads/".$id."/".$row->img_name_tn);
unlink("uploads/".$id."/".$row->file);
unlink("uploads/".$id."/".$row->file2);
unlink("uploads/".$id."/Thumbs.db");
}
rmdir("uploads/".$id);
}
here is the code i used but it delete the files at ones. and how can i delete all files from the folder?
originally from php.net:
<?php
$dir = '/uploads/';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if ($file != "." && $file != "..") { // strip the current and previous directory items
unlink($dir . $file); // you can add some filters here, aswell, to filter datatypes, file, prefixes, suffixes, etc
}
}
closedir($handle);
}
?>
I found this at php.net:
"The shortest recursive delete possible"
function rrmdir($path) {
return is_file($path)?
#unlink($path):
array_map('rrmdir',glob($path.'/*'))==#rmdir($path)
;
}
You could do it like this:
function delete_files($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);
}
}
closedir($dir_handle);
return true;
}
You need to use a recursive function. A comment from the rmdir page have written a function on how to do it, see http://www.php.net/manual/en/function.rmdir.php#98622. This code will delete the folder and everything in it.
<?php
function rrmdir($dir) {
if (is_dir($dir)) {
$objects = scandir($dir);
foreach ($objects as $object) {
if ($object != "." && $object != "..") {
if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object);
}
}
reset($objects);
rmdir($dir);
}
}
?>