What are best practices for handling form data and writing it to a text file in PHP?

When handling form data in PHP, it is important to sanitize and validate the input to prevent security vulnerabilities such as SQL injection or cross-site scripting attacks. Once the data is validated, it can be written to a text file using file handling functions like fopen, fwrite, and fclose. It is also recommended to store the data in a structured format like JSON or CSV for easier retrieval and manipulation.

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

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

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

// Close the file
fclose($file);