Question

The following code deletes the files in a folder uploads.How do I delete the folder as well when a user clicks Delete Folder (or similar).

I tried using rmdir but I am not getting errors only blank move.php file.

What's the correct/recommended way of doing it ? Please advice.

    <?php
    $actfolder = $_REQUEST['folder'];
    require_once("models/config.php");

    if(!securePage($_SERVER['PHP_SELF'])){
        die();
    }
    require("models/db-settings.php");

    if(isset($_GET['file'])){
        $filename = "uploads/$loggedInUser->username$actfolder/" . ltrim($_GET['file'], '/\\');
        // make sure only deleting a file in files/ directory
        if (dirname(realpath($filename)) == realpath("uploads/$loggedInUser->username$actfolder/")) {
            unlink($filename);
        }
    }
    header("Location:".$_SERVER["HTTP_REFERER"]);
?>
Was it helpful?

Solution

Just try something like this:

$filename = "uploads/$loggedInUser->username$actfolder/";
if (is_dir($filename) === true)
    {
        $files = array_diff(scandir($filename), array('.', '..'));

        foreach ($files as $file)
        {
           unlink(realpath($filename) . '/' . $file);
        }

        rmdir($filename);  //remove directory
    }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top