What are the best practices for handling file deletion in PHP to avoid permission errors?

When deleting files in PHP, it is important to ensure that the script has the necessary permissions to delete the file. One common issue is encountering permission errors when trying to delete files that the script does not have permission to access. To avoid this, it is recommended to check if the file exists and if the script has the appropriate permissions before attempting to delete it.

$file_path = 'path/to/file.txt';

// Check if the file exists and the script has permission to delete it
if (file_exists($file_path) && is_writable($file_path)) {
    // Delete the file
    if (unlink($file_path)) {
        echo "File deleted successfully.";
    } else {
        echo "Error deleting file.";
    }
} else {
    echo "File does not exist or permission denied.";
}