[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

PHP Recursively Delete Directory

Posted on 2007-08-02
17
Medium Priority
?
2,193 Views
Last Modified: 2013-12-13
Hi,

I'm trying to write a PHP function which takes a directory path as a parameter, and then deletes all files and subdirectories. So far I have:

function delete_directory($dirname){
      if  (is_dir($dirname))
          chmod($dirname, 0755);    
            $dir_handle  =  opendir($dirname);
    if  (!$dir_handle)
        return  false;
    //while($file = readdir($dir_handle)){
    while (($file = readdir($dir_handle)) !== false){
        if  ($file  !=  "."  &&  $file  !=  "..")  {
            if  (is_dir($dirname."/".$file)){
                      delete_directory($dirname.'/'.$file);
            } else {
                  unlink($dirname."/".$file);
            }
        }
    }
    closedir($dir_handle);  
    rmdir($dirname);
}

But running this I get the warning:
"Warning: rmdir(C:/xampp/xampp/htdocs/temp) [function.rmdir]: Directory not empty"

When I view the file in Windows Explorer, the directory is empty (with show hidden/system files turned on!), and if I do "dir" from the command line, the only entries are "." and ".."

I'm a bit confused, becuase the directory does appear to be empty - any ideas?

Thanks
0
Comment
Question by:kchall
  • 9
  • 7
17 Comments
 
LVL 40

Expert Comment

by:Richard Quadling
ID: 19615708
Try this ...

<?php
function delete_directory($dirname)
 {
 if (is_dir($dirname))
  {
  exec "rm /s /q $dirname";
  }
 }
?>
0
 
LVL 40

Expert Comment

by:Richard Quadling
ID: 19615763
Many files/folders are held open by applications.

Download SysInternals Process Explorer and find the handle of the temp folder and see what application has it open.

Depending upon how it has opened the handle, will determine if it can be deleted or not.

And a temp folder is pretty important to most OS's. I would not recommend deleting it.

0
 
LVL 1

Author Comment

by:kchall
ID: 19615768
That doesnt appear to do anything at all unfortunately...
0
Concerto Cloud for Software Providers & ISVs

Can Concerto Cloud Services help you focus on evolving your application offerings, while delivering the best cloud experience to your customers? From DevOps to revenue models and customer support, the answer is yes!

Learn how Concerto can help you.

 
LVL 40

Expert Comment

by:Richard Quadling
ID: 19615775
Did you call the function?
0
 
LVL 1

Author Comment

by:kchall
ID: 19615780
"And a temp folder is pretty important to most OS's. I would not recommend deleting it."
That is just an example path - I've tried it on several file paths.
0
 
LVL 1

Author Comment

by:kchall
ID: 19615788
"Did you call the function?"
Yes, and tried a couple of different flags on the exec call

exec('rm - r '.$dirname);

did nothing either.
0
 
LVL 40

Expert Comment

by:Richard Quadling
ID: 19615791
Yep. MANY paths and files are locked.

This is normal.

If you have an application or a service which has locked a file or folder, you have to stop the app  or service before you can delete the file.

Some files are locked by the OS and cannot be deleted by a user.
0
 
LVL 1

Author Comment

by:kchall
ID: 19615805
The odd thing about it is that the directories this is being applied to are created by an earlier part of my PHP script, and this delete function is part of a rollback process in my error handling.
0
 
LVL 40

Accepted Solution

by:
Richard Quadling earned 1050 total points
ID: 19615820
I've created a copy of one of my directorys (C:\MD5 => C:\Copy of MD5).

<?php
function delete_directory($dirname)
 {
 if (is_dir($dirname))
  {
  exec("rmdir /s /q \"$dirname\"", $a_Output);
  }
 return $a_Output;
 }

print_r(delete_directory('C:/Copy of MD5'));
?>

This outputs ...

Array
(
)

indicating no problems.

0
 
LVL 40

Expert Comment

by:Richard Quadling
ID: 19615824
Running it a second time outputs a notice ...

Notice: Undefined variable: a_Output in C:\dp.php on line 8

Which is fine as this isn't a real script, just a tester. So I know the script is working.
0
 
LVL 40

Expert Comment

by:Richard Quadling
ID: 19615826
If you take the test out, then the result is the same.
0
 
LVL 1

Author Comment

by:kchall
ID: 19615856
I've copied your test function into my code, and called the output - the returned array $a_Output is empty as in your test, but I am still left with the empty directory not being deleted.
0
 
LVL 40

Expert Comment

by:Richard Quadling
ID: 19615914
Can you do it by hand. As a test.
0
 
LVL 1

Author Comment

by:kchall
ID: 19616290
Deleting by hand works fine.

Confused...
0
 
LVL 11

Assisted Solution

by:AlexanderR
AlexanderR earned 450 total points
ID: 19616440
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)) {
         return FALSE;
     }
     else {
         $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;
     }
 }

recursive_remove_directory("C:/xampp/xampp/htdocs/temp");
0
 
LVL 1

Author Comment

by:kchall
ID: 19616717
I was looking at a function very similar to that on the PHP manual pages, and I still get the same problem - PHP still thinks the folder isnt empty. all I can think is that PHP has still got some temporary file lock somehow - but as I'm not creating any locks I cant see how this could happen
0
 
LVL 40

Expert Comment

by:Richard Quadling
ID: 19616829
Like I said, use System Internals Process Explorer or their Handles program to find the lock.

http://www.microsoft.com/technet/sysinternals/default.mspx

http://www.microsoft.com/technet/sysinternals/Utilities/ProcessExplorer.mspx
http://www.microsoft.com/technet/sysinternals/SystemInformation/Handle.mspx

It would probably be worth putting the PHP code into a LONG delay whilst you examined this issue.
0

Featured Post

VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Part of the Global Positioning System A geocode (https://developers.google.com/maps/documentation/geocoding/) is the major subset of a GPS coordinate (http://en.wikipedia.org/wiki/Global_Positioning_System), the other parts being the altitude and t…
3 proven steps to speed up Magento powered sites. The article focus is on optimizing time to first byte (TTFB), full page caching and configuring server for optimal performance.
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
Suggested Courses
Course of the Month20 days, 7 hours left to enroll

868 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question