In what ways can the PHP script be optimized for security and best practices, considering the use of user input in writing to a file?

To optimize the PHP script for security when writing user input to a file, it is crucial to sanitize and validate the input to prevent malicious code injection. One way to achieve this is by using PHP's `filter_input` function to validate the input data before writing it to the file. Additionally, it is recommended to set proper file permissions to restrict access to the file.

$user_input = filter_input(INPUT_POST, 'user_input', FILTER_SANITIZE_STRING);

if ($user_input !== false) {
    $file = 'data.txt';
    $handle = fopen($file, 'a');
    fwrite($handle, $user_input . "\n");
    fclose($handle);
    chmod($file, 0644); // Set file permissions
} else {
    echo 'Invalid input';
}