How can one ensure the security of file deletion operations in PHP?

When deleting files in PHP, it is important to ensure that the operation is secure to prevent unauthorized access or accidental deletion of important files. One way to enhance security is by checking if the file exists before attempting to delete it and verifying the user's permissions. Additionally, using a whitelist approach for allowed file deletions can help prevent malicious file deletions.

<?php
$filename = "example.txt";

// Check if the file exists and user has permission to delete
if (file_exists($filename) && is_writable($filename)) {
    // Perform the file deletion
    unlink($filename);
    echo "File deleted successfully.";
} else {
    echo "Unable to delete file. Please check file permissions or file existence.";
}
?>