dongying7667 2018-06-26 23:49
浏览 116
已采纳

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-26 23: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();
    ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
编辑
预览

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部