When performing log analysis, we usually need to count the frequency of occurrence of different IP addresses. PHP provides many powerful built-in functions to help us handle such tasks. Today we will introduce how to use the array_count_values function to count the occurrence frequency of each IP in the log. Here is a sample code showing how to use the function.
First, let’s take a look at the structure of the log. Suppose we have a log file, each line records an access request, in the format as follows:
2025-04-17 12:34:56 192.168.1.1 /home
2025-04-17 12:35:00 192.168.1.2 /about
2025-04-17 12:36:01 192.168.1.1 /contact
2025-04-17 12:37:02 192.168.1.3 /home
2025-04-17 12:38:05 192.168.1.1 /blog
The above log records the IP address of each visitor and the page path to be accessed. Our goal is to count how often each IP address appears in the log.
We first need to read the content of the log file into PHP, which can be implemented using file functions or file_get_contents .
<?php
// Read log files
$log = file('path_to_log_file.log');
?>
Next, we need to extract the IP address from each line. Assuming that the IP address of each row is recorded in the second field of the log, we can divide the content of each row through the exploit function and then extract the IP address.
<?php
// Initialize an empty array store IP address
$ips = [];
foreach ($log as $line) {
// Split each line with spaces,Assumptions IP It's the second field
$parts = explode(' ', $line);
// Will IP address添加到数组中
$ips[] = $parts[1];
}
?>
Once we extract all IP addresses, we can use PHP's array_count_values function to count the occurrence frequency of each IP address.
<?php
// statistics IP address出现的频率
$ip_counts = array_count_values($ips);
// Output result
foreach ($ip_counts as $ip => $count) {
echo "IP: $ip - Count: $count\n";
}
?>
If we have the following log:
2025-04-17 12:34:56 192.168.1.1 /home
2025-04-17 12:35:00 192.168.1.2 /about
2025-04-17 12:36:01 192.168.1.1 /contact
2025-04-17 12:37:02 192.168.1.3 /home
2025-04-17 12:38:05 192.168.1.1 /blog
After running the PHP code above, the output will be:
IP: 192.168.1.1 - Count: 3
IP: 192.168.1.2 - Count: 1
IP: 192.168.1.3 - Count: 1
Suppose our log also contains URLs, and the domain names of these URLs need to be replaced with m66.net . We can use the str_replace function to implement it.