Writing Daily Log Files in PHP Applications
Logging user actions, particularly authentication events like logins, is a foundational requirement for security auditing and debugging. The core challenge often isn't writing to a file at all, but ensuring that file handles behave correctly across multiple requests and that the filename itself adheres to your specific daily rotation requirements.
In your example, you are working within a controller or service layer where you handle authentication logic. To log this event, you need to access the filesystem safely. PHP provides several ways to write data, but for server-side logging, file_put_contents() is generally preferred over manually opening files with fopen(). The primary reason is simplicity: file_put_contents handles the underlying file handle creation and closure automatically, preventing "file already open" errors that occur when you forget to call fclose().
Generating Unique Daily Filenames
Your requirement for a single file per day means the filename must be dynamic. You can achieve this by combining the current date string with a fixed extension. Using PHP's date() function is the standard approach here.
$date = date('Y-m-d'); // e.g., "2023-10-27"
$logFile = '/var/log/myapp/auth_' . $date . '.log';
This pattern ensures that logs from October 27th do not overwrite logs from October 28th. However, you must ensure the directory exists and is writable before attempting to write. If your application runs as a specific user (like www-data), that user must have write permissions for the target directory. A common pitfall is assuming /var/log/myapp exists; if it doesn't, the script will throw an "No such file or directory" error. You should verify the path and create the directory with appropriate permissions (chmod 755) during your deployment process.
Implementing the Log in Your Authentication Flow
To integrate logging into your existing hasAccess method without disrupting the flow, you should append a concise message to the log file. The format of this message is up to you, but including the timestamp, username (if safe), and the action type is best practice.
Be cautious about what you log. While logging usernames is helpful for tracking who logged in, never log raw passwords or sensitive tokens. In your provided code snippet, you are already hashing or checking credentials via SecurityDAO, so ensure that $username passed to the logger has been sanitized if it contains special characters that might break the log format.
public function hasAccess($username, $password) {
// ... existing logic to get $result ...
if ($result[0]['success'] == '1') {
// Perform logging before setting session
$logMessage = "User {$username} authenticated successfully at " . date('Y-m-d H:i:s');
file_put_contents($logFile, $logMessage . PHP_EOL, FILE_APPEND);
$this->Session->add('user_id', $result[0]['id']);
return $this->status(0, true, 'auth.success', $result);
} else {
// Optional: Log failed attempts for security monitoring
$logMessage = "User {$username} failed authentication at " . date('Y-m-d H:i:s');
file_put_contents($logFile, $logMessage . PHP_EOL, FILE_APPEND);
return $this->status(0, false, 'auth.failed', $result);
}
}
Managing Log Growth and Format
As your application grows, appending to a single text file can lead to massive files that slow down your system or make searching difficult. A common industry standard is to use the syslog facility if you are on Linux, which handles rotation automatically. However, if you stick to custom file logging, consider using a structured format like JSON for each line instead of plain text.
$logEntry = [
'timestamp' => date('Y-m-d H:i:s'),
'action' => 'LOGIN',
'user' => $username, // Ensure this is escaped if not already
'status' => 'SUCCESS'
];
$jsonLog = json_encode($logEntry);
file_put_contents($logFile, $jsonLog . PHP_EOL, FILE_APPEND | LOCK_EX);
Using LOCK_EX with file_put_contents adds an exclusive lock, preventing two concurrent requests from writing to the same file simultaneously and corrupting the data stream. This is critical in high-traffic environments.
For more complex logging needs, such as rotating logs after they reach a certain size or keeping only the last 30 days of entries, look into existing PHP logging libraries like Monolog. These tools handle complexity that is easy to implement incorrectly from scratch. If you are building on top of Laravel, integrating Monolog via the laravelcompany.com resources can streamline this process significantly, allowing you to configure log channels directly in your config/logging.php.