What are the best practices for securely deleting files in PHP, especially when using user input?

When securely deleting files in PHP, especially when using user input, it is important to validate and sanitize the input to prevent any malicious file deletion. One common approach is to use the `unlink()` function along with proper input validation to ensure that only allowed files are deleted.

// Validate and sanitize user input
$filename = filter_var($_POST['filename'], FILTER_SANITIZE_STRING);

// Define the directory where the files are stored
$directory = '/path/to/files/';

// Check if the file exists in the specified directory
if (file_exists($directory . $filename)) {
    // Delete the file
    unlink($directory . $filename);
    echo 'File deleted successfully.';
} else {
    echo 'File not found.';
}