What are some best practices for logging web server requests in PHP to identify potential issues with duplicate entries?
When logging web server requests in PHP, one common issue is the possibility of duplicate entries being logged, which can make it difficult to identify and troubleshoot potential issues. To prevent this, one best practice is to check if the log entry already exists before writing a new entry to the log file.
// Check if the log entry already exists before writing to the log file
$logFile = 'requests.log';
$logEntry = 'New log entry to be added';
if (file_exists($logFile)) {
$logContent = file_get_contents($logFile);
if (strpos($logContent, $logEntry) === false) {
file_put_contents($logFile, $logEntry . PHP_EOL, FILE_APPEND);
}
} else {
file_put_contents($logFile, $logEntry . PHP_EOL);
}