What are some best practices for handling form submissions in PHP, especially when storing user input in a file?

When handling form submissions in PHP and storing user input in a file, it is important to sanitize and validate the user input to prevent any security vulnerabilities such as SQL injection or cross-site scripting attacks. Additionally, it is recommended to use file locking mechanisms to prevent race conditions when writing to the file. Finally, consider implementing error handling to gracefully handle any issues that may arise during the submission process.

<?php
// Sanitize and validate user input
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

// File path to store user input
$file = 'user_data.txt';

// Write user input to file with file locking
if ($fp = fopen($file, 'a')) {
    if (flock($fp, LOCK_EX)) {
        fwrite($fp, "Name: $name, Email: $email\n");
        flock($fp, LOCK_UN);
    }
    fclose($fp);
} else {
    echo "Error writing to file.";
}
?>