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 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 下图接收小电路,谁知道原理
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测