How can you improve the security of the PHP script to prevent directory traversal attacks or unauthorized file deletions?

Directory traversal attacks and unauthorized file deletions can be prevented by sanitizing user input and properly validating file paths before performing any file operations. One way to improve the security of a PHP script is to use the realpath() function to resolve the full path of a file and ensure that it is within the expected directory.

// Sanitize and validate the file path
$file_path = '/path/to/directory/' . $_POST['file'];

// Get the real path of the file
$real_path = realpath($file_path);

// Check if the real path is within the expected directory
if (strpos($real_path, '/path/to/directory/') === 0) {
    // Perform file operations
    unlink($real_path);
} else {
    // Handle unauthorized file deletion
    echo "Unauthorized file deletion";
}