Are there any best practices for handling file and folder deletion in PHP scripts?

When deleting files and folders in PHP scripts, it is important to handle errors and permissions properly to avoid unexpected behavior or security vulnerabilities. One best practice is to check if the file or folder exists before attempting to delete it, and to use functions like unlink() for files and rmdir() for folders. Additionally, it is recommended to set appropriate file permissions and to sanitize user input to prevent directory traversal attacks.

// Example code for deleting a file in PHP
$filename = 'example.txt';

if (file_exists($filename)) {
    if (unlink($filename)) {
        echo 'File deleted successfully';
    } else {
        echo 'Error deleting file';
    }
} else {
    echo 'File does not exist';
}