基於 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 分鐘內在網站有活動的人數。