dongying7667 2018-06-27 07:49
浏览 115
已采纳

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

I'm trying to make a unique hit counter with PHP based on the IP address of the user.

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."
");
        fclose($handle);
    }
}

As you can see it pretty much takes the IP address of the user and then calls the text document 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.

And after that, it opens up count.txt in order to count the hits. In the end, it will add the IP address to ip.txt as well.

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.

  • 写回答

1条回答 默认 最新

  • dp9599 2018-06-27 07:56
    关注

    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."
    ", 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();
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大