What is the best practice for saving data from a guestbook to a TXT file in PHP?
When saving data from a guestbook to a TXT file in PHP, it is best practice to properly sanitize and validate the input data to prevent any security vulnerabilities. Additionally, it is recommended to use file handling functions to write the data to the TXT file securely.
<?php
// Sanitize and validate input data
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$message = filter_var($_POST['message'], FILTER_SANITIZE_STRING);
// Open the TXT file in append mode
$file = fopen('guestbook.txt', 'a');
// Write the data to the file
fwrite($file, "Name: $name\nMessage: $message\n\n");
// Close the file
fclose($file);
echo "Data saved successfully!";
?>