How important is sanitizing user input in PHP when writing to log files compared to other scenarios?

Sanitizing user input in PHP when writing to log files is crucial to prevent malicious code injection or unintended formatting issues. It is important to sanitize user input by removing or escaping special characters that could potentially disrupt the log file structure or execute harmful commands. This can be achieved by using functions like htmlspecialchars() or addslashes() before writing the input to the log file.

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

// Write sanitized input to log file
$logFile = fopen('log.txt', 'a');
fwrite($logFile, $sanitizedInput . PHP_EOL);
fclose($logFile);