What are some best practices for storing form data in a .txt file using PHP?

When storing form data in a .txt file using PHP, it's important to ensure that the data is properly sanitized to prevent any security vulnerabilities. One common approach is to serialize the form data before writing it to the file, making it easier to retrieve and manipulate later. Additionally, it's a good practice to use file locking to prevent concurrent write operations that could corrupt the data.

// Sanitize and serialize form data
$form_data = serialize($_POST);

// Open the file for writing with file locking
$file = fopen('form_data.txt', 'a');
if (flock($file, LOCK_EX)) {
    fwrite($file, $form_data . PHP_EOL);
    flock($file, LOCK_UN);
}
fclose($file);