What are some best practices for implementing a custom logging system in PHP to track user activities, such as failed login attempts, and ensure data security and integrity?
To implement a custom logging system in PHP to track user activities like failed login attempts, it is essential to create a secure and efficient solution. One way to achieve this is by creating a separate log file for each type of activity, such as login attempts, and ensuring that sensitive information is not logged in plaintext. Additionally, consider implementing log rotation to manage log file sizes and prevent them from becoming too large.
<?php
// Function to log user activities
function logActivity($activity, $username) {
$logFile = 'activity_log_' . $activity . '.txt';
$logMessage = "[" . date('Y-m-d H:i:s') . "] User " . $username . " attempted " . $activity . "\n";
// Ensure log directory exists and is writable
if (!is_dir('logs')) {
mkdir('logs');
}
// Write log message to file
file_put_contents('logs/' . $logFile, $logMessage, FILE_APPEND);
}
// Example usage
$username = 'john_doe';
logActivity('login_attempt', $username);
?>
Related Questions
- What are some common debugging techniques recommended for PHP scripts like the one described?
- Why is it recommended to use UTF-8 encoding instead of iso-8859-1 when sending emails with PHP?
- What are the potential pitfalls of using ternary operators within echo statements in PHP for string concatenation?