How can PHP developers ensure that user input is secure when writing to log files and prevent potential security vulnerabilities?

To ensure that user input is secure when writing to log files in PHP, developers should sanitize and validate the input before writing it to the log file. This can help prevent potential security vulnerabilities such as SQL injection or cross-site scripting attacks. One way to sanitize user input is by using functions like htmlentities() or addslashes() to escape special characters.

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

// Write sanitized input to log file
$logFile = 'logs.txt';
$logMessage = date('Y-m-d H:i:s') . ' - ' . $sanitizedInput . PHP_EOL;
file_put_contents($logFile, $logMessage, FILE_APPEND);