What are the best practices for handling user input in PHP to prevent malicious file deletion?

To prevent malicious file deletion in PHP when handling user input, it is essential to sanitize and validate the input before using it to delete files. One way to do this is by checking if the input corresponds to a file that the user is allowed to delete, such as by comparing it against a list of safe file paths or IDs. Additionally, limiting the permissions of the PHP script to only delete files within a specific directory can help mitigate the risk of unauthorized file deletions.

// Example code snippet to prevent malicious file deletion in PHP

// Sanitize and validate the user input
$fileToDelete = $_POST['fileToDelete'];
$allowedFiles = ['file1.txt', 'file2.txt', 'file3.txt']; // List of safe file paths

if (in_array($fileToDelete, $allowedFiles)) {
    // Check if the file exists before attempting to delete it
    $filePath = '/path/to/files/' . $fileToDelete;
    if (file_exists($filePath)) {
        // Limit the deletion to files within a specific directory
        $directory = '/path/to/files/';
        if (strpos(realpath($filePath), realpath($directory)) === 0) {
            // Delete the file
            unlink($filePath);
            echo 'File deleted successfully.';
        } else {
            echo 'Unauthorized file deletion attempt.';
        }
    } else {
        echo 'File does not exist.';
    }
} else {
    echo 'Invalid file.';
}