刚用PHP写了一个网站在线人数的程序,请大家进来指点下!
刚用PHP写了一个网站在线人数的程序,请大家进来指点下!%F7t%MwU@ C'x,t,]'G我是用PHP+MYSQL来写的,原理:网站在线人数的程序代码+后台有MYSQL数据库支持,可以直接统计出网站当前的在线人数。5h\%{GJ
首先我创建MYSQL数据库表。
CREATE TABLE tablename (
field type(max_length) DEFAULT 'default_value' (NOT) NULL B#^-M q$Lm
}可以使用的SQL语句。H*{1u1U:v/NE
CREATE TABLE useronline (YMm7l0d/~`n2XnY
timestamp int(15) DEFAULT '0' NOT NULL, RF0ug,RrOD0t}5Y
ip varchar(40) NOT NULL,E?)z4p7A Gw
file varchar(100) NOT NULL,
PRIMARY KEY (timestamp),
KEY ip (ip),
KEY file (file)P[7g,Z7J/?f
);下面我们是PHP脚本,首先我定义MYSQL的信息。
$server = "localhost"; //你的服务器6d3C*Xc.yT
$db_user = "root"; //你的mysql的用户名
$db_pass = "password"; //你的mysql的密码
$database = "users"; //表的名字设置统计的时间(多少秒内在线人数)
$timeoutseconds = 300;取当前时间。5X(Q+}L&y&fDV
$timestamp = time();上面的完整代码:0m-}5Ge;_N;q
<?php
$server = "localhost"; //your server0GN)kS6Ooo
$db_user = "root"; //your mysql database username c l0|kx%^
$db_pass = "password"; //your mysql database password if any
$database = "users"; //the db name;OOCg{7ez
$timeoutseconds = 300;//timeoutseconds limit
//get the current time
$timestamp = time();
//calculate the lowest timestamp allowed)t`C ?(n-i?og%mB
$timeout = $timestamp-$timeoutseconds;.i#s8q.lDR%M m
?>连接mysqlV'rKn4H+E:w Yn&K
mysql_connect('localhost', 'username', 'password');也允许使用变量形式。
mysql_connect($server, $db_user, $db_pass);如果mysql数据库没有密码的话可以使用下面代码连接#iS)G9TU$rml5H P:P
mysql_connect($server, $db_user);查询数据库的代码::tXu;QW/~(sf
mysql_db_query('database', 'query');我们只要有访客就要增加一条记录。3cN5m7c6i!B1Ur9C@
$insert = mysql_db_query($database, "INSERT INTO useronline VALUES
('$timestamp','".$_SERVER['REMOTE_ADDR']."','".$_SERVER['PHP_SELF']."')");&cOCh4^ bg;?
如果用户用错误信息的话,这样处理。
if(!($insert)) {i] m1w2p+o$Y3}7b
print "Useronline Insert Failed > ";
}然后实现当超过设置的时间就删除该用户记录。
$delete = mysql_db_query($database, "DELETE FROM useronline WHERE timestamp<$timeout");同样给出删除记录出错的处理。qLE0t(h8CcM
if(!($delete)) {ar9w9D-a Iq~n
print "Useronline Delete Failed > "; P.s-Y$Imo*mu8W
}下面我们解决数据库中不同IP的问题
$result = mysql_db_query($database, "SELECT DISTINCT ip FROM useronline WHERE file='".$_SERVER['PHP_SELF']."' ");使用9j};{3cTguC2|
mysql_num_rows(query);来统计用户,代码如下。
$user = mysql_num_rows($result);最后关闭数据库。Y-B}2U"j!c2Q
mysql_close();显示在线的人数。+aOLtG|4Q
if($user == 1) {
print("1 user online\n");
} else {
print("$user users online\n");
}最终把上面代码写成一个PHP文件如下。;D2[5w{lA/]W
<?php
//Put your basic server info here
$server = "localhost"; //normally localhost
$db_user = "root"; //your MySQL database username E&~ ^4^m8IbkI
$db_pass = "password"; //your MySQL database password
$database = "users";
$timeoutseconds = 300; //it will delete all people which haven't refreshed(so probbably are
// offline or inactive) in $timieoutseconds time (so it actually checks the people that are active in the last
// $timeoutseconds seconds)
//this is where PHP gets the timeB D*zFF%r t
$timestamp = time();