Are there any potential security risks or vulnerabilities when writing user input directly to a text file in PHP?

When writing user input directly to a text file in PHP, there is a risk of allowing malicious code to be injected into the file, potentially leading to security vulnerabilities such as code execution or file manipulation. To mitigate this risk, it is important to properly sanitize and validate user input before writing it to the file.

$userInput = $_POST['user_input'];

// Sanitize and validate user input before writing to file
$sanitizedInput = filter_var($userInput, FILTER_SANITIZE_STRING);

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