What are some best practices for implementing file deletion functionality in a PHP script to ensure data integrity and security?

When implementing file deletion functionality in a PHP script, it is important to ensure data integrity and security by validating user input, checking file permissions, and using secure deletion methods. One best practice is to sanitize user input to prevent directory traversal attacks and only allow deletion of files within a specific directory. Additionally, check if the file exists and if the user has the necessary permissions to delete it before proceeding with the deletion.

<?php
// Validate user input and sanitize file path
$filePath = '/path/to/files/' . basename($_POST['fileToDelete']);

// Check if file exists and user has permission to delete it
if (file_exists($filePath) && is_writable($filePath)) {
    // Use secure deletion method to remove the file
    if (unlink($filePath)) {
        echo 'File deleted successfully.';
    } else {
        echo 'Failed to delete file.';
    }
} else {
    echo 'File not found or permission denied.';
}
?>