簡體   English   中英

PHP唯一命中計數器不起作用

[英]PHP Unique Hit Counter Does Not Work

我正在嘗試根據用戶的IP地址使用PHP創建一個唯一的計數器。

這是我的嘗試:

$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);
    }
}

如您所見,它幾乎占用了用戶的IP地址,然后調用了文本文檔ip.txt 因此,如果用戶IP地址的比較與該文本文檔中存儲的IP地址不匹配,它將返回false

之后,它會打開count.txt以計算點擊數。 最后,它將IP地址也添加到ip.txt中。

但是現在,此代碼的問題在於它沒有執行必須執行的操作。 我的意思是即使執行后兩個文本文件都為空。

而且也不會出現錯誤,因為代碼編寫正確。

所以我的問題是,這段代碼有什么問題,我該如何解決?

提前致謝。

幾天前,我創建了類似的功能。 這是我的代碼,請嘗試一下。

<?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