Is there a best practice for handling file deletion in PHP to ensure security and efficiency?

When deleting files in PHP, it is important to ensure both security and efficiency. One best practice is to always validate user input to prevent directory traversal attacks. Additionally, it is recommended to check if the file exists before attempting to delete it to avoid unnecessary errors.

// Validate user input to prevent directory traversal attacks
$filename = 'path/to/files/' . basename($_POST['filename']);

// Check if the file exists before attempting to delete it
if (file_exists($filename)) {
    unlink($filename);
    echo 'File deleted successfully.';
} else {
    echo 'File not found.';
}