What are common pitfalls when using PHP to handle form data and write to a CSV file?
Common pitfalls when using PHP to handle form data and write to a CSV file include not properly sanitizing user input, not checking for file permissions, and not handling errors effectively. To solve these issues, always sanitize user input to prevent SQL injection or other attacks, ensure that the CSV file has the correct permissions for writing, and use error handling to catch any issues that may arise during the process.
<?php
// Sanitize user input
$name = filter_var($_POST['name'], FILTER_SANITIZE_STRING);
$email = filter_var($_POST['email'], FILTER_SANITIZE_EMAIL);
// Check file permissions
$csvFile = 'data.csv';
if (!is_writable($csvFile)) {
die('Cannot write to CSV file. Check file permissions.');
}
// Write to CSV file
$data = [$name, $email];
$fp = fopen($csvFile, 'a');
if ($fp) {
fputcsv($fp, $data);
fclose($fp);
echo 'Data written to CSV file successfully.';
} else {
echo 'Error writing to CSV file.';
}
?>