PHP網(wǎng)站在線人數(shù)
Jun 08, 2016 pm 05:32 PM
剛用PHP寫(xiě)了一個(gè)網(wǎng)站在線人數(shù)的程序,請(qǐng)大家進(jìn)來(lái)指點(diǎn)下!
我是用PHP+MYSQL來(lái)寫(xiě)的,原理:網(wǎng)站在線人數(shù)的程序代碼+后臺(tái)有MYSQL數(shù)據(jù)庫(kù)支持,可以直接統(tǒng)計(jì)出網(wǎng)站當(dāng)前的在線人數(shù)。
首先我創(chuàng)建MYSQL數(shù)據(jù)庫(kù)表。
CREATE TABLE tablename (
field type(max_length) DEFAULT 'default_value' (NOT) NULL
}可以使用的SQL語(yǔ)句。
CREATE TABLE useronline (
timestamp int(15) DEFAULT '0' NOT NULL,
ip varchar(40) NOT NULL,
file varchar(100) NOT NULL,
PRIMARY KEY (timestamp),
KEY ip (ip),
KEY file (file)
);下面我們是PHP腳本,首先我定義MYSQL的信息。
$server = "localhost"; //你的服務(wù)器
$db_user = "root"; //你的mysql的用戶(hù)名
$db_pass = "password"; //你的mysql的密碼
$database = "users"; //表的名字設(shè)置統(tǒng)計(jì)的時(shí)間(多少秒內(nèi)在線人數(shù))
$timeoutseconds = 300;取當(dāng)前時(shí)間。
$timestamp = time();上面的完整代碼:
$server = "localhost"; //your server
$db_user = "root"; //your mysql database username
$db_pass = "password"; //your mysql database password if any
$database = "users"; //the db name
$timeoutseconds = 300;//timeoutseconds limit
//get the current time
$timestamp = time();
//calculate the lowest timestamp allowed
$timeout = $timestamp-$timeoutseconds;
?>連接mysql
mysql_connect('localhost', 'username', 'password');也允許使用變量形式。
mysql_connect($server, $db_user, $db_pass);如果mysql數(shù)據(jù)庫(kù)沒(méi)有密碼的話(huà)可以使用下面代碼連接
mysql_connect($server, $db_user);查詢(xún)數(shù)據(jù)庫(kù)的代碼:
mysql_db_query('database', 'query');我們只要有訪客就要增加一條記錄。
$insert = mysql_db_query($database, "INSERT INTO useronline VALUES
('$timestamp','".$_SERVER['REMOTE_ADDR']."','".$_SERVER['PHP_SELF']."')");
如果用戶(hù)用錯(cuò)誤信息的話(huà),這樣處理。
if(!($insert)) {
print "Useronline Insert Failed > ";
}然后實(shí)現(xiàn)當(dāng)超過(guò)設(shè)置的時(shí)間就刪除該用戶(hù)記錄。
$delete = mysql_db_query($database, "DELETE FROM useronline WHERE timestamp
if(!($delete)) {
print "Useronline Delete Failed > ";
}下面我們解決數(shù)據(jù)庫(kù)中不同IP的問(wèn)題
$result = mysql_db_query($database, "SELECT DISTINCT ip FROM useronline WHERE file='".$_SERVER['PHP_SELF']."' ");使用
mysql_num_rows(query);來(lái)統(tǒng)計(jì)用戶(hù),代碼如下。
$user = mysql_num_rows($result);最后關(guān)閉數(shù)據(jù)庫(kù)。
mysql_close();顯示在線的人數(shù)。
if($user == 1) {
print("1 user online\n");
} else {
print("$user users online\n");
}最終把上面代碼寫(xiě)成一個(gè)PHP文件如下。
//Put your basic server info here
$server = "localhost"; //normally localhost
$db_user = "root"; //your MySQL database username
$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 time
$timestamp = time();
//counts the timeout, all people which have been seen last online in earlier than this timestamp, will get removed
$timeout = $timestamp-$timeoutseconds;
//connect to database
mysql_connect($server, $db_user);
//add the timestamp from the user to the online list
$insert = mysql_db_query($database, "INSERT INTO useronline VALUES
('$timestamp','".$_SERVER['REMOTE_ADDR']."','".$_SERVER['PHP_SELF']."')");
if(!($insert)) {
print "Useronline Insert Failed > ";
}
//delete the peoples which haven't been online/active in the last $timeoutseconds seconds.
$delete = mysql_db_query($database, "DELETE FROM useronline WHERE timestamp
if(!($delete)) {
print "Useronline Delete Failed > ";
}
//select the amount of people online, all uniques, which are online on THIS page
$result = mysql_db_query($database, "SELECT DISTINCT ip FROM useronline WHERE file='".$_SERVER['PHP_SELF']."' ");
if(!($result)) {
print "Useronline Select Error > ";
}
//Count the number of rows = the number of people online
$user = mysql_num_rows($result);
//spit out the results
mysql_close();
if($user == 1) {
print("1 user online\n");
} else {
print("$user users online\n");
}
?>
?
?

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

To reset the root password of MySQL, please follow the following steps: 1. Stop the MySQL server, use sudosystemctlstopmysql or sudosystemctlstopmysqld; 2. Start MySQL in --skip-grant-tables mode, execute sudomysqld-skip-grant-tables&; 3. Log in to MySQL and execute the corresponding SQL command to modify the password according to the version, such as FLUSHPRIVILEGES;ALTERUSER'root'@'localhost'IDENTIFIEDBY'your_new

When handling NULL values ??in MySQL, please note: 1. When designing the table, the key fields are set to NOTNULL, and optional fields are allowed NULL; 2. ISNULL or ISNOTNULL must be used with = or !=; 3. IFNULL or COALESCE functions can be used to replace the display default values; 4. Be cautious when using NULL values ??directly when inserting or updating, and pay attention to the data source and ORM framework processing methods. NULL represents an unknown value and does not equal any value, including itself. Therefore, be careful when querying, counting, and connecting tables to avoid missing data or logical errors. Rational use of functions and constraints can effectively reduce interference caused by NULL.

mysqldump is a common tool for performing logical backups of MySQL databases. It generates SQL files containing CREATE and INSERT statements to rebuild the database. 1. It does not back up the original file, but converts the database structure and content into portable SQL commands; 2. It is suitable for small databases or selective recovery, and is not suitable for fast recovery of TB-level data; 3. Common options include --single-transaction, --databases, --all-databases, --routines, etc.; 4. Use mysql command to import during recovery, and can turn off foreign key checks to improve speed; 5. It is recommended to test backup regularly, use compression, and automatic adjustment.

Turn on MySQL slow query logs and analyze locationable performance issues. 1. Edit the configuration file or dynamically set slow_query_log and long_query_time; 2. The log contains key fields such as Query_time, Lock_time, Rows_examined to assist in judging efficiency bottlenecks; 3. Use mysqldumpslow or pt-query-digest tools to efficiently analyze logs; 4. Optimization suggestions include adding indexes, avoiding SELECT*, splitting complex queries, etc. For example, adding an index to user_id can significantly reduce the number of scanned rows and improve query efficiency.

TosecurelyconnecttoaremoteMySQLserver,useSSHtunneling,configureMySQLforremoteaccess,setfirewallrules,andconsiderSSLencryption.First,establishanSSHtunnelwithssh-L3307:localhost:3306user@remote-server-Nandconnectviamysql-h127.0.0.1-P3307.Second,editMyS

GROUPBY is used to group data by field and perform aggregation operations, and HAVING is used to filter the results after grouping. For example, using GROUPBYcustomer_id can calculate the total consumption amount of each customer; using HAVING can filter out customers with a total consumption of more than 1,000. The non-aggregated fields after SELECT must appear in GROUPBY, and HAVING can be conditionally filtered using an alias or original expressions. Common techniques include counting the number of each group, grouping multiple fields, and filtering with multiple conditions.

MySQL transactions and lock mechanisms are key to concurrent control and performance tuning. 1. When using transactions, be sure to explicitly turn on and keep the transactions short to avoid resource occupation and undolog bloating due to long transactions; 2. Locking operations include shared locks and exclusive locks, SELECT...FORUPDATE plus X locks, SELECT...LOCKINSHAREMODE plus S locks, write operations automatically locks, and indexes should be used to reduce the lock granularity; 3. The isolation level is repetitively readable by default, suitable for most scenarios, and modifications should be cautious; 4. Deadlock inspection can analyze the details of the latest deadlock through the SHOWENGINEINNODBSTATUS command, and the optimization methods include unified execution order, increase indexes, and introduce queue systems.

MySQL paging is commonly implemented using LIMIT and OFFSET, but its performance is poor under large data volume. 1. LIMIT controls the number of each page, OFFSET controls the starting position, and the syntax is LIMITNOFFSETM; 2. Performance problems are caused by excessive records and discarding OFFSET scans, resulting in low efficiency; 3. Optimization suggestions include using cursor paging, index acceleration, and lazy loading; 4. Cursor paging locates the starting point of the next page through the unique value of the last record of the previous page, avoiding OFFSET, which is suitable for "next page" operation, and is not suitable for random jumps.
