What potential pitfalls should be considered when logging user actions in PHP?

Potential pitfalls when logging user actions in PHP include storing sensitive information in logs, not properly sanitizing user input before logging, and exposing log files to unauthorized users. To mitigate these risks, ensure that only necessary information is logged, sanitize user input before writing to logs, and restrict access to log files.

// Example of logging user actions in PHP with proper input sanitization and access control

// Sanitize user input before logging
$userAction = filter_var($_POST['user_action'], FILTER_SANITIZE_STRING);

// Log user action to a file
$logFile = 'user_actions.log';
$logMessage = date('Y-m-d H:i:s') . ' - User performed action: ' . $userAction . PHP_EOL;
file_put_contents($logFile, $logMessage, FILE_APPEND);

// Restrict access to log files
// Place log files outside of the web root directory or use .htaccess to restrict access