tags:

views:

39

answers:

3

I've built a system whereby users can start a project and upload files to this project. When they create the project, I create a directory specifically for that project and all uploads fill this directory. However, I have implemented a system that allows the user to remove this project if they wish, deleting all the files within the directory and then the directory itself.

Locally (on MAMP), this worked a charm; on a live server however, it doesn't. For the directory removal I used a stock piece of code from a tutorial website (posted below) and as I said, works fine on a local webserver.

$name = $_POST['projectName'];
rrmdir("../../project/$name");

    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);
        echo "Directory Removed";
    }
+2  A: 

Noticing your use of relative paths please see if this comment helps: http://php.net/manual/en/function.unlink.php#85938

Rob Olmos
+2  A: 

Try this one instead:

$iterator = new RecursiveIteratorIterator(
    new RecursiveDirectoryIterator('/path/to/project/directory'),
    RecursiveIteratorIterator::CHILD_FIRST);

foreach($iterator as $fileObject) {
    if($fileObject->isFile()) {
        echo 'Removing File: ', $fileObject->getRealpath(), PHP_EOL;
        // unlink($fileObject->getRealpath());
    } elseif($fileObject->isDir()) {
        echo 'Removing Dir: ', $fileObject->getRealpath(), PHP_EOL;
        // rmdir($fileObject->getRealpath());
    }
}

Uncomment the rmdir and unlink lines to actually perform the removals.

Gordon
+2  A: 

Be very careful with this:

$name = $_POST['projectName'];
rrmdir("../../project/$name");

That's like an SQL injection for your server's file system, imagine if someone types this in to their browser: http://www.yoursite.com/this-script.php?projectName=../../../../var/www You'll probably want to look at escapeshellarg() to help close this gaping security hole and realpath() to convert the relative path in to an absolute one. If the target dir isn't empty then rmdir won't work, you need to remove all of the subdirs and files first before rmdir will work.

Robin
Thanks for this, but the post comes from a drop-down list of their projects, this field isn't editable. Thanks though
Daniel Hanly
A form is just a GUI to the actual POST data. This POST data is easily forged or can be intercepted and mangled with an addon like Tamper Data (https://addons.mozilla.org/en-US/firefox/addon/966/). Here's an excellent app/teaching into web security:http://google-gruyere.appspot.com/
Rob Olmos