What are the best practices for logging search keywords in PHP?

Logging search keywords in PHP can help track user behavior and improve search functionality. To implement this, you can capture the search query parameter from the URL, sanitize it to prevent SQL injection or XSS attacks, and then log it to a file or database. It's important to handle logging securely to protect user privacy and data.

// Get the search query parameter from the URL
$searchQuery = isset($_GET['q']) ? $_GET['q'] : '';

// Sanitize the search query to prevent SQL injection or XSS attacks
$sanitizedQuery = filter_var($searchQuery, FILTER_SANITIZE_STRING);

// Log the search query to a file
$logFile = 'search.log';
$logMessage = date('Y-m-d H:i:s') . " - Search Query: " . $sanitizedQuery . PHP_EOL;
file_put_contents($logFile, $logMessage, FILE_APPEND);