What are the potential issues with directly writing user input to a text file in PHP?

Directly writing user input to a text file in PHP can lead to security vulnerabilities such as code injection or file manipulation. To prevent this, it is important to sanitize and validate user input before writing it to a file. One way to do this is by using PHP's `htmlspecialchars()` function to escape special characters in the input data.

// Sanitize user input before writing to a text file
$userInput = htmlspecialchars($_POST['user_input']);

// Open the file for writing
$file = fopen('user_data.txt', 'a');

// Write the sanitized user input to the file
fwrite($file, $userInput . "\n");

// Close the file
fclose($file);