Page 1 of 1

Deleting folder recursively

Posted: Tue Sep 19, 2006 12:00 am
by Skeptical
What is the best way to delete a folder recursively in PHP? Right now all solutions involve iterating through every single subfolder and removing all files before being allowed to delete a folder. Is there anything out there in PHP that will let me do this faster?

Re: Deleting folder recursively

Posted: Tue Sep 19, 2006 2:28 am
by arkady
Skeptical wrote:What is the best way to delete a folder recursively in PHP? Right now all solutions involve iterating through every single subfolder and removing all files before being allowed to delete a folder. Is there anything out there in PHP that will let me do this faster?
Depending on the OS running the server, you could just run an exec command (provided you knew exactly what you were doing)

ie.

Code: Select all

$my_remove_command = 'rm -rf ' . $mypath;
exec($my_remove_command,  $tmp);
foreach ($tmp as $result)
{
  print($result.'<BR>');
}
If you're going to use it, be -very- careful about what gets passed.. maybe do a reg_exp check to make sure that '..' isn't passed etc.

Posted: Tue Sep 19, 2006 5:58 am
by Jenk
always use realpath() when dealing with directories. Then check that the submitted directory is within your sandbox.

On a shared host it's unlikely you'll have access to exec() and even if you do, it's very unlikely you'll be able to actually execute anything.. expecially 'rm' or such.

If you absolutely must do this via php:

Code: Select all

<?php

function ClearDirs ($dir)
{
    if (!($dir = realpath($dir))) return;

    $handle = opendir($dir);

    while (($file = readdir($handle)) !== false)
    {
        $fullpath = realpath($dir . DIRECTORY_SEPARATOR . $file);
        if (is_file($fullpath))
        {
            unlink($fullpath);
        }
        elseif (is_dir($file) && !in_array($file, array('.', '..')))
        {
            ClearDirs($fullpath);
        }
    }
}

?>
Be careful with it..

Posted: Tue Sep 19, 2006 11:53 pm
by Skeptical
Thanks for your tips.

Doing it via a system call would be the easiest, but there are a couple of issues:

1) Security. Enabling system calls in php.ini could potentially expose my server to hackers.

2) "rm -rf" still has a limitation. If too many files/folders exist, the "rm" command will fail.

Basically, I'm just trying to figure out the most efficient way to let a user delete a folder and all of its contents. My app is in PHP so my thinking is that if the code can be contained within PHP, then it'll be easier to manage. However, if that's not the case, I'd be open to your suggestions.

Btw, I own the server so I can do whatever I want.[/list][/list]