PHP delete folder


Answers ( 1 )


    To delete a folder in PHP, you can use the rmdir() function if the folder is empty. However, if the folder contains files or subdirectories, you'll need to first recursively delete these contents. Here's how you can do it:

    PHP Code to Delete a Non-Empty Folder

    function deleteFolder($folderPath) {
        // Ensure there's a trailing slash at the end of the folder path
        $folderPath = rtrim($folderPath, '/') . '/';
        // Open the folder
        $items = scandir($folderPath);
        foreach ($items as $item) {
            if ($item != "." && $item != "..") {
                // Full path to the item
                $path = $folderPath . $item;
                // Check if the item is a directory
                if (is_dir($path)) {
                    // Recursively delete the directory
                } else {
                    // It's a file; delete it
        // Delete the main folder
    // Usage


    1. Function Definition: deleteFolder is a recursive function that takes a folder path as its parameter.

    2. Normalization of Folder Path: It ensures the folder path ends with a slash for consistency.

    3. Reading Directory Contents: scandir() reads the contents of the folder.

    4. Iterating Over Items: Loop through each item in the folder.

    5. Ignoring Special Directories: Skip . and .. as they refer to the current and parent directory, respectively.

    6. Recursion for Subdirectories: If an item is a directory, the function calls itself recursively to delete that subdirectory.

    7. Deleting Files: If an item is a file, it is deleted using unlink().

    8. Removing the Main Folder: After clearing its contents, the main folder is deleted with rmdir().


    • Replace 'path/to/your/folder' with the actual path of the folder you want to delete.

    Important Notes:

    • This script will delete all contents of the folder irreversibly. Use it with caution.
    • Make sure you have the necessary permissions to delete the folder and its contents.
    • This script doesn't handle exceptions or errors, like permission issues or files being used by other processes. You might want to add error handling as per your requirements.

Leave an answer