How can PHP developers track and log file deletion activities for auditing purposes?
To track and log file deletion activities for auditing purposes in PHP, developers can use a combination of file system functions and logging mechanisms. One approach is to create a custom function that logs the details of file deletions, such as the file name, deletion timestamp, and user performing the deletion. This function can be called whenever a file deletion operation is executed in the PHP code.
function logFileDeletion($filename, $username) {
$logMessage = "File '$filename' was deleted by user '$username' at " . date('Y-m-d H:i:s') . PHP_EOL;
file_put_contents('deletion_log.txt', $logMessage, FILE_APPEND);
}
// Example usage
$filename = 'example.txt';
$username = 'john_doe';
unlink($filename); // Perform the file deletion
logFileDeletion($filename, $username); // Log the file deletion