PHP statistics on online users

Source: Internet
Author: User
Create   Table 'User _ online '(
'Session'
Varchar ( 100 ) Not   Null   Default   '' ,
'Time'
Int ( 11 ) Not   Null   Default   ' 0 '  
) Type
= MyISAM;

 

Code

<? PHP
Session_start ();
$ Session = Session_id ();
$ Time = Time ();
 
// $ Time_check is used to detect timeout
$ Time_check = $ Time - 600 ; // Set the time to 10 minutes = 10*60 seconds
 
$ Host = " Localhost " ; // Host Name
$ Username = " Root " ; // MySQL U User Name
$ Password = " 123456 " ; // MySQL password
$ Db_name = " Test " ; // Database Name
$ Tbl_name = " User_online " ; // Table Name
 
// Connect to the server and select the database

Mysql_connect ( " $ Host " ,   " $ Username " ,   " $ Password " ) Or Die ( " Unable to connect to MySQL Service " );
Mysql_select_db ( " $ Db_name " ) Or Die ( " Unable to select database " );
 
$ SQL = " Select * from $ Tbl_name Where session =' $ Session ' " ;
$ Result = Mysql_query ( $ SQL ); // Execute Query
 
$ Count = Mysql_num_rows ( $ Result );
 
// Check whether the specified session exists. Otherwise, insert a record.
If ( $ Count = " 0 " ){
// The specified session does not exist.
$ Sql1 = " Insert $ Tbl_name (Session, time) values (' $ Session ',' $ Time ') " ;
$ Result1 = Mysql_query ( $ Sql1 ); // Insert
} Else {
$ Sql2 = " Update $ Tbl_name Set Time =' $ Time 'Where session =' $ Session ' " ;
$ Result2 = Mysql_query ( $ Sql2 ); // If yes, modify the connection time.
}
 
$ Sql3 = " Select * from $ Tbl_name " ;
$ Result3 = Mysql_query ( $ Sql3 );
 
$ Count_user_online = Mysql_num_rows ( $ Result3 ); // The number of sessions is counted to determine the number of online users.
 
Echo   " Online users: $ Count_user_online   " ;
 
// Delete the timeout session record. The user connected 10 minutes ago is deemed to have timed out.
$ Sql4 = " Delete from $ Tbl_name Where time < $ Time_check " ;
$ Result4 = Mysql_query ( $ Sql4 );
 
Mysql_close ();
 
// Open multiple browsers to test
?>

 

Auto: http://hi.baidu.com/fanglor/blog/item/55eb194bbb9026fc83025c5c.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.