How to use a PHP session to display the current online user

Source: Internet
Author: User
Tags add time function prototype functions header variables php file php session variable
Show | Online This is what I wrote a while ago, to thank you for your help.
=============

Review
PHP session refers to the user from entering the site to the closure of the site during the period of a mechanism, it provides all web pages are common use of the public variable storage mechanism. So what is the use of the session? When shopping on the Internet, everyone has used a shopping cart, you can always add the goods you buy to the shopping cart, and finally go to the cashier checkout. Throughout the process, the shopping cart has been playing the role of temporary storage of selected goods, using it to track the user's activities on the site, this is the role of the session.
The session's invention fills the limits of the HTTP protocol, which is considered a stateless protocol, and the server loses contact with the browser when it completes its response on the service side. The invention of the session allows a user to save his information when switching between multiple pages.
In the PHP3 version does not provide a direct session function, we can only use other methods to achieve, such as using Phplib. If PHP4 compared with PHP3, its greatest improvement is to provide a session.

Session Basics
To use the session, you need to PHP4.1 the above version, and you need to set the Register_globle=off in PHP.ini to Register_globle=on. In addition, Session.cookie_path =/This line is not easy to change.
The session in PHP is by default a cookie used by the client. When the client's cookie is disabled, it is automatically passed through the query_string.

There are 11 functions in the PHP processing session, and we'll talk about several functions we'll use.
1, Session_Start
function function: Start a session or return a session that already exists.
Function prototype: Boolean session_start (void);
Return Value: Boolean value
Function Description: This function has no parameters and the return value is true. It is best to place this function first, and there is no output before it, otherwise it will alarm, such as: Warning:cannot send session cache Limiter-headers already sent (output started At/us R/local/apache/htdocs/cga/member/1.php:2) in/usr/local/apache/htdocs/cga/member/1.php on line 3
2, Session_register
function function: Register a new variable as session variable
Function prototype: Boolean Session_register (string name);
Return value: Boolean value.
Function Description: This function is to add a variable in the global variable to the current session, the parameter name is the name of the variable you want to join, and success returns the logical value TRUE. You can use the form of $_session[name] or $http_session_vars[name] to take a value or assign a value.
3, session_is_registered
function function: Checks whether a variable is registered as a session variable.
Function prototype: Boobean session_is_registered (string name);
Return Value: Boolean value
Function Description: This function checks whether the specified variable is registered in the current session, and the parameter name is the variable name to check. Success returns the logical value TRUE.
4, Session_unregister
function function: Deletes a registered variable.
Function prototype: Boolean Session_session_unregister (string name);
Return Value: Boolean value
Function Description: This function deletes the variables in the global variable in the current session. The parameter name is the name of the variable you want to delete, and success returns TRUE.
5, Session_destroy
function function: Ends the current session and empties all resources in the session.
Function Prototype: Boolean session destroy (void);
Return value: Boolean value.
Function Description: This function ends the current session, this function has no arguments, and the return value is True

The functions described above will be used, but there are also some functions about the session:
6, Session_encode
function function: sesssion information encoding
Function prototype: string session_encode (void);
return value: String
Function Description: The returned string contains the names and values of the variables in the global variable in the form of: A|s:12: "It is a test"; C|s:4: "Lala"; A is the variable name s:12 represents the value of variable a "it is a test length is a semicolon between 12 variables"; Separated.
7, Session_decode
function function: sesssion information decoding
Function prototype: Boolean Session_decode (String data)
Return Value: Boolean value
Function Description: This function can decode session information, success returns the logical value TRUE
8, Session_name
function function: Accessing the current session name
Function prototype: Boolean session_name (string [name]);
return value: String
Function Description: This function can get or reset the name of the current session. Without the parameter name, the current session name is obtained, plus the parameter indicates that the session name is set to the parameter name
9, session_id
function function: Accessing the current session identification number
Function prototype: Boolean session_id (string [id]);
return value: String
Function Description: This function can get or reset the identification number of the current session. The absence of a parameter ID means that only the identification number of the current session is obtained, plus the parameter indicates that the session's identification number is set to the newly specified ID
10, Session_unset
function function: Deletes all registered variables.
Function prototype: void Session_unset (void)
Return Value: Boolean value
Function Description: This function is different from Session_destroy, it does not end the session. Just like using a function session_unregister to log off all of the session variables.



Programming Ideas
In the community, the forum, we often see the current online members, so that visitors feel at home. But how does this procedure work out?

The process is as follows:











Create a table user and save registered users information.
Field type notes
UserID Int (10) User serial number auto_increment keyword
Username Varchar (50) User nickname
Userpwd Varchar (50) password
Email Varchar (50) email
Oicq Varchar (m) Oicq
Signature Mediumtext Signature
Imgurl Varchar (50) head
Joindate Varchar (50) Add time
Building class file user.php defining functions
exist ($username) confirm that the new registered user is already present
Nsert ($username, $userpwd, $email, $oicq, $imgurl, $signature) Insert registered user
Update ($userid, $username, $userpwd, $email, $oicq, $imgurl, $signature) updating user data
Get_from_condition ($con) returns the recordset that satisfies the query criteria

Create a table session. Inserts a new record into the table when the user logs in, deletes the record after leaving or times out, and guarantees that the table holds the current online user.
Field type notes
SessionID Int (10) serial number auto_increment keyword
UserID Int (10) User serial number is taken from the users table
IPAddress Varchar IP Address
LastActivity Int (10) Last activity time, use it to determine whether the user is still online
Building class file session.php defining functions
Insert ($userid, $ipaddress, $lastactivity) inserts a successful user into the table
Update ($userid, $ipaddress, $lastactivity) updating online user last activity time
Del ($con) remove users who meet the criteria and use it to clear offline users
Get_from_condition ($con) returns the recordset that satisfies the query criteria

Common file global.php
Include "class/config.inc.php"; Include the configuration file in
$DB = new db;
$db-> db_connect (); Connecting to a database
$user = new User; Class
$session = new Session;

Start session
Session_Start ();
Delete users who have expired in the session table (that is, non-online users) because this file is always invoked to ensure that the current online user is displayed
$curtime =time ();
$con = "lastactivity< $curtime";
$session->del ($con);

Online users need to constantly update the session table LastActivity time, and reset the user's Cookies
if ($HTTP _session_vars["online"]== "on") {//Here is also available $_session[' online ']
$userid = $HTTP _session_vars["userid"]; Take the current online user's UserID
$ipaddress =substr ($REMOTE _addr,0,50);
$lastactivity =time () +3600; Update the last activity time, such as if the page is not transferred within one hours, the user is considered offline and will be deleted.
$session->update ($userid, $ipaddress, $lastactivity);
}else{
If you are not logged in, go directly to the login page
$firstpage = "logon.php";
Header ("Location: $firstpage");
Exit
}
Login File logon.php
?    Include "global.php"; Include the global.php file in

if ($hiddenField = = "0") {//test form has not been submitted

$con = "Username= ' $username ' and userpwd= ' $userpwd '";
$result = $user->get_from_condition ($con);
if ($user->counter==1) {
if (!session_is_registered ("online")) {//detect has been registered
Session_register ("online"); Register a new variable as a session variable
}
if (!session_is_registered ("Ccauser")) {
Session_register ("Ccauser");
}
if (!session_is_registered ("userid")) {
Session_register ("userid");
}
$ccauser = $username; Assign a value to a session variable
$online = "on"; This variable is used in global.php to update the last activity time lastactivity
$userid = $user->userid;
$ipaddress =substr ($REMOTE _addr,0,50);
$lastactivity =time () +3600;
$con = "Userid= $userid";
$session->get_from_condition ($con);
To determine if a session exists, you may be able to log on to a different machine two times.
if ($session->counter==1) {
$session->update ($userid, $ipaddress, $lastactivity); If present, update
}else{
$session->insert ($userid, $ipaddress, $lastactivity); If not present, insert
}

Set up cookies on the client
Setcookie ("Ccauser", $username, Time () +3600);
Header ("Location:test.php");//Then guide the test page
}
}
?>
?
if ($HTTP _session_vars["online"]== "") {//To determine whether you are logged in
?>
Here is the form for the login
<form name= "Form1" method= "Post" action= "" >
Name: <input type= "text" name= "username" >
Password: <input type= "text" name= "Userpwd" >
<input type= "hidden" name= "HiddenField" value= "0" >
<input type= "Submit" name= "Submission" value= "submitted" >
<input type= "reset" name= "Submit2" value= "reset" >
</form>
?
}else{
echo "net friend:" $HTTP _cookie_vars["Ccauser"]. " You have logged in "; Show prompts if you are logged on
$str = "<br><br><a href= ' exit.php ' > Exit Community </a>";
Echo $str;
}
?>

Test file test.php
?
Include "global.php"; Include the global.php file in
$strWelcome = "Welcome to <font color=red>". $_session[' Ccauser '. " </font><br> ";
Echo $strWelcome; Show Welcome Information
$str = "Current online user:<br>===================<br>";
$con = "1=1";
All the records in the session table are the current online users, not counting the visitors
$result = $session->get_from_condition ($con);
while ($row =mysql_fetch_array ($result)) {

$con 1= "userid= $row [UserID]";
$user->get_from_condition ($con 1);
$str. = $user->username. " ";
}
Echo $str;
?>
<br><a href= ' exit.php ' > Exit Community </a>

Exit file exit.php
?
Include "global.php"; Include the global.php file in
if ($_session["online"]== "on") {
$con = "Userid= $userid";
$session->del ($con); Deletes user information in the session table.
Session_destroy (); Ends the current session and empties all resources in the session
echo "has withdrawn from the community ...";
}
?>


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.