PHP Recursively Delete Directory

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
LVL 1
kchallAsked:
Who is Participating?
 
Richard QuadlingConnect With a Mentor Senior Software DeveloperCommented:
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
 
Richard QuadlingSenior Software DeveloperCommented:
Try this ...

<?php
function delete_directory($dirname)
 {
 if (is_dir($dirname))
  {
  exec "rm /s /q $dirname";
  }
 }
?>
0
 
Richard QuadlingSenior Software DeveloperCommented:
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
Cloud Class® Course: CompTIA Cloud+

The CompTIA Cloud+ Basic training course will teach you about cloud concepts and models, data storage, networking, and network infrastructure.

 
kchallAuthor Commented:
That doesnt appear to do anything at all unfortunately...
0
 
Richard QuadlingSenior Software DeveloperCommented:
Did you call the function?
0
 
kchallAuthor Commented:
"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
 
kchallAuthor Commented:
"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
 
Richard QuadlingSenior Software DeveloperCommented:
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
 
kchallAuthor Commented:
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
 
Richard QuadlingSenior Software DeveloperCommented:
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
 
Richard QuadlingSenior Software DeveloperCommented:
If you take the test out, then the result is the same.
0
 
kchallAuthor Commented:
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
 
Richard QuadlingSenior Software DeveloperCommented:
Can you do it by hand. As a test.
0
 
kchallAuthor Commented:
Deleting by hand works fine.

Confused...
0
 
AlexanderRConnect With a Mentor Enterprise Web DeveloperCommented:
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
 
kchallAuthor Commented:
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
 
Richard QuadlingSenior Software DeveloperCommented:
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
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.