With the rapid growth of the internet, website operators increasingly value collecting and analyzing user behavior data. By recording access logs, one can accurately understand visitor paths and visit frequency, providing data support for site optimization. This article introduces how to implement access log recording and analysis with PHP, including practical code examples.
To record access logs, PHP's built-in file handling functions can be used to write visitor information into a log file. The following example demonstrates how to log the visitor's IP address, access time, and visited page:
<?php // Get the user's IP address $ip = $_SERVER['REMOTE_ADDR']; // Get the user's access time $time = date('Y-m-d H:i:s'); // Get the requested page URL $page = $_SERVER['REQUEST_URI']; // Construct the log entry, using tabs to separate fields $log = "$ip $time $page "; // Append the log entry to the access.log file file_put_contents('access.log', $log, FILE_APPEND); ?>
This code reads the client's IP, request time, and URI, then constructs and appends a log line to the access.log file, effectively recording access logs.
Once access logs are recorded, analyzing the log contents helps to count page visits and identify popular pages. The following code shows how to read the log file and count visits per page:
<?php // Read the contents of the log file $logContent = file_get_contents('access.log'); // Split the log content into an array by line $logArray = explode("\n", $logContent); // Define an array to count page visits $pageCount = array(); // Iterate through each log entry foreach ($logArray as $logLine) { // Split log entry fields by tab $logData = explode(" ", $logLine); // Get the page URL $page = isset($logData[2]) ? $logData[2] : ''; // Count page visits if (!empty($page)) { if (isset($pageCount[$page])) { $pageCount[$page]++; } else { $pageCount[$page] = 1; } } } // Sort pages by visit count in descending order arsort($pageCount); // Output the visit statistics foreach ($pageCount as $page => $count) { echo "$page $count "; } ?>
This code reads the log file line by line, splits each entry, counts the visits per page, and outputs the sorted results, allowing developers to quickly understand traffic distribution.
This article explained the basic methods to implement website access log recording and analysis using PHP. With simple file writing and reading operations, developers can build an access logging system to assist in website data analysis and optimization. We hope this guide provides practical reference for PHP developers.