What best practices should be followed when writing PHP code to process and store form data in a .txt file?

When processing and storing form data in a .txt file using PHP, it is essential to sanitize and validate the input data to prevent security vulnerabilities such as SQL injection and cross-site scripting attacks. Additionally, it is crucial to properly handle file operations, such as opening, writing, and closing the file, to ensure data integrity and avoid file system errors.

// Sanitize and validate form data
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);

// Open the file for writing
$file = fopen('data.txt', 'a');

// Write the form data to the file
fwrite($file, "Name: $name\nEmail: $email\n\n");

// Close the file
fclose($file);