基於 HTTP 协议的限制,要实现统计联机人数会很困难。而现时大部份网站或论坛所使用的方法是,统计在过去某段时间內有所活动的访客,便计算为联机人数,本文会介绍使用 PHP + MySQL 制作一个联机人数计数器。
在开始前请先确定网页服务器支持 PHP 4.3.x,以及有一个可用的 MySQL 数据库,如果沒有 MySQL 数据库,请向你的系统管理员或网页寄存供应商查询。
创建数据库
----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
第一步需要先创建一个 MySQL 数据表,可以在文字模式或 phpmyadmin 下执行以下 SQL 语句:
PHP 代码:
01 CREATE TABLE `online_counter`(
02 `hash` varchar(50) not null,
03 `remote_addr` varchar(20) not null,
04 `time` int(10) not null)
PHP 代码
-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
当创建以上数据表后,便可以编写 PHP 程序了,以下例子假设你的 MySQL 登录数据如下:
Host: localhost
username: dbuser
password: dbpasswd
database: dbname
请注意,在使用以下代码时,请根据你的实际需要修改 MySQL 登录数据:
PHP 代码:
01 <?php
02 // create mysql connection
03 $db_conn = mysql_connect("localhost", "dbuser", "dbpasswd");
04 mysql_select_db("dbname", $db_conn);
05
06 // check and make hash string
07 if(!isset($_SESSION["hash"])){
08 $hash = md5(time());
09 session_register("hash");
10 $_SESSION["hash"] = $hash;
11 }
12
13 // update database
14 $time = time();
15 $query = mysql_query("select hash from `online_counter` where hash='".$_SESSION["hash"]."'");
16 if($rows = mysql_fetch_row($query)){
17 mysql_query("update `online_counter` set `time`='".$time."' where hash='".$_SESSION["hash"]."'");
18 }else{
19 mysql_query("insert into `online_counter` values('".$_SESSION["hash"]."', '".$_SERVER["REMOTE_ADDR"]."', '".$time."')");
20 }
21
22 // get online users
23 $counter_time = $time - 600; // 10 mins
24 $online_query = mysql_query("select count(*) as total from `online_counter` where `time` > '".$counter_time."'");
25 $online_counter = mysql_fetch_array($online_query);
26
27 // delete old record
28 mysql_query("delete from `online_counter` where `time` < '".$counter_time."'");
29 ?>
在以上例子,$online_counter['total'] 就是在过去 10 分钟內在网站有活动的人数。