简体   繁体   中英

PHP - My own counter - Trouble

I made my own custom counter, to count people that connect on my website. This is the code :

$date=date("Y-m-d H:i:s");
$ip=$_SERVER['REMOTE_ADDR'];
$query=mysql_query("SELECT date, id FROM views WHERE ip='$ip' ORDER BY date DESC",$mydb);

if(mysql_num_rows($query)!=0){
    $id_ip=mysql_result($query,0,'id');
    $limit_time=strtotime("-20 minutes");
    $current_time=strtotime(mysql_result($query,0,'date'));
} else {
    $limit_time=$date;
    $current_time=0;
}

if(isset($_SESSION['nickname'])) {
    $user=$_SESSION['nickname'];
} else {
    $user="gtw@visitor";
}

if($current_time<$limit_time) {         
    $insert=mysql_query("INSERT INTO views (ip, user, date) VALUES ('$ip', '$user', '$date')", $mydb);
} else {
    if($user!="gtw@visitor") {
        $update=mysql_query("UPDATE views SET date='$date', user='$user' WHERE id='$id_ip'",$mydb);
    } else {
        $update=mysql_query("UPDATE views SET date='$date' WHERE id='$id_ip'",$mydb);
    }
}

Problem is this : if I connect to the website with the same IP (so, the same computer for example) with 2 browser, which I'll log with 2 different username, It just count as a single visitor. Any suggestion to better this situation?

Maybe add for each connection an HASH generated from BROWSER AGENT? Dunno...

As you have noticed, many clients can share the same public IP address.

Google gets around this problem by using a cookie. This isn't foolproof, but is about the best you can do. You can use this method to also track the sequence of pages visited on your site.

Really though, you should just use an off-the-shelf analytics package, such as Google Analytics .

You could set a cookie and check to see if exists before you add to the counter, though that might give you some other issues. You might want to look at how the wordpress stat counter is implemented, or, alternatively, go for google analytics (unless you really want to roll your own :))

You can add the user agent string to the views table so that each visit would consist of the tuple (IP, Date, User agent). This would help count visits from the same IP on different browsers as two different visits.

You can get the user agent string using $_SERVER['HTTP_USER_AGENT'].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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