What are some best practices for handling file manipulation in PHP, specifically when it comes to deleting files based on user input?

When deleting files based on user input in PHP, it is important to validate and sanitize the user input to prevent any security vulnerabilities such as directory traversal attacks. Additionally, it is recommended to check if the file exists before attempting to delete it to avoid errors. Finally, always handle errors gracefully and provide feedback to the user if the file deletion was successful or not.

<?php
// Validate and sanitize user input
$filename = $_POST['filename'];
$filename = basename($filename);

// Check if the file exists before deleting
if (file_exists($filename)) {
    // Attempt to delete the file
    if (unlink($filename)) {
        echo "File deleted successfully.";
    } else {
        echo "Failed to delete the file.";
    }
} else {
    echo "File not found.";
}
?>