What best practices should be followed when handling form submissions and writing to files in PHP, as seen in the code snippet provided?

When handling form submissions and writing to files in PHP, it is important to sanitize user input to prevent security vulnerabilities like SQL injection or cross-site scripting attacks. Additionally, it is crucial to validate the data before writing it to a file to ensure it meets the expected format. Using PHP's built-in functions like htmlentities() for sanitization and fopen() for file writing can help mitigate these risks.

// Sanitize form input
$name = htmlentities($_POST['name']);
$email = htmlentities($_POST['email']);

// Validate data
if (!empty($name) && !empty($email)) {
    // Write data to file
    $file = fopen('data.txt', 'a');
    fwrite($file, "Name: $name, Email: $email\n");
    fclose($file);
    echo "Data written successfully";
} else {
    echo "Please fill out all fields";
}