What are the potential security risks associated with CSV injection in PHP?
CSV injection in PHP occurs when user input is not properly sanitized before being inserted into a CSV file, allowing an attacker to inject malicious code that can be executed when the CSV file is opened in a program like Excel. To prevent CSV injection, user input should be properly sanitized by escaping special characters and using functions like `fputcsv()` to write data to the CSV file.
// Sanitize user input before writing to CSV file
$user_input = $_POST['user_input'];
$escaped_input = str_replace(array("\n", "\r", "\t"), '', $user_input); // Remove newline, carriage return, and tab characters
$fp = fopen('data.csv', 'a');
fputcsv($fp, array($escaped_input));
fclose($fp);