What are some potential security risks associated with saving user input directly to files in PHP applications?

Saving user input directly to files in PHP applications can lead to security risks such as code injection attacks, where malicious code can be inserted into the file and executed when accessed by the application. To mitigate this risk, it is important to sanitize and validate user input before saving it to files. One way to do this is by using functions like htmlspecialchars() to escape special characters and prevent code injection.

// Sanitize and validate user input before saving to file
$userInput = $_POST['user_input'];
$sanitizedInput = htmlspecialchars($userInput);

$file = fopen("user_data.txt", "w");
fwrite($file, $sanitizedInput);
fclose($file);