简体   繁体   English

PHP唯一命中计数器不起作用

[英]PHP Unique Hit Counter Does Not Work

I'm trying to make a unique hit counter with PHP based on the IP address of the user. 我正在尝试根据用户的IP地址使用PHP创建一个唯一的计数器。

This is my attempt: 这是我的尝试:

$ip_address = $_SERVER["REMOTE_ADDR"];

function hit_count(){
    $ip_file = file('ip.txt');
    foreach($ip_file as $ip){
        $ip_single = trim($ip);
        if($ip_address == $ip_single){
            $found = true;
            break;
        }else{
            $found = false;
        }
    }
    if($found == false){
        $filename = "count.txt";
        $handle = fopen($filename,"r");
        $current = fread($handle,filesize($filename));
        fclose($handle);
        $current_inc = $current + 1;
        $handle = fopen($filename,"w");
        fwrite($handle,$current_inc);
        fclose($handle);
        $handle = fopen("ip.txt","a");
        fwrite($handle,$ip_address."\n");
        fclose($handle);
    }
}

As you can see it pretty much takes the IP address of the user and then calls the text document ip.txt . 如您所见,它几乎占用了用户的IP地址,然后调用了文本文档ip.txt So if the comparison of user's IP address was not matched with the IP address that is stored in that text document, it will return false . 因此,如果用户IP地址的比较与该文本文档中存储的IP地址不匹配,它将返回false

And after that, it opens up count.txt in order to count the hits. 之后,它会打开count.txt以计算点击数。 In the end, it will add the IP address to ip.txt as well. 最后,它将IP地址也添加到ip.txt中。

But now the problem with this code is that it does not do what it must do. 但是现在,此代码的问题在于它没有执行必须执行的操作。 I mean both text files are empty even after the execution. 我的意思是即使执行后两个文本文件都为空。

And no errors also appear because the codes are written correctly. 而且也不会出现错误,因为代码编写正确。

So my question is, what is wrong with this code, and how can I fix that? 所以我的问题是,这段代码有什么问题,我该如何解决?

Thanks in advance. 提前致谢。

I had created a similar functionality a few days back. 几天前,我创建了类似的功能。 here is my code do try it out. 这是我的代码,请尝试一下。

<?php
$filename = 'count.txt';
$ip_filename = 'ip.txt';
function hit_count(){
    $ip = get_ip();
    global $filename, $ip_filename;

    if(!in_array($ip, file($ip_filename, FILE_IGNORE_NEW_LINES))){
        $current_value = (file_exists($filename)) ? file_get_contents($filename) : 0;
        file_put_contents($ip_filename, $ip."\n", FILE_APPEND);
        file_put_contents($filename, ++$current_value);
    }
}
function get_ip(){
if(!empty($_SERVER['HTTP_CLIENT_IP'])){
    $ip_address = $_SERVER['HTTP_CLIENT_IP'];
}else if(!empty($_SERVER['HTTP_X_FORWARDED_FOR'])){
    $ip_address = $_SERVER['HTTP_X_FORWARDED_FOR'];
}else{
    $ip_address = $_SERVER['REMOTE_ADDR'];
}
return $ip_address;
}
hit_count();
?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM