What are some best practices for saving form data to a file in PHP?

When saving form data to a file in PHP, it is important to properly sanitize and validate the data before writing it to the file to prevent security vulnerabilities. Additionally, it is recommended to use a secure file path and handle file writing errors gracefully.

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

// Define file path
$file = 'data.txt';

// Write form data to file
$data = "Name: $name\nEmail: $email\n";

if(file_put_contents($file, $data, FILE_APPEND) !== false){
    echo "Data saved successfully.";
} else {
    echo "Error saving data.";
}