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