Front End Learning PHP conversation session

Source: Internet
Author: User
Tags session id

Previous words

Session technology is similar to a cookie and is used to store information about users. The big difference, however, is that the cookie stores the data in the client's computer, while the session stores the data under the server system. The Chinese meaning of the session is the conversation, in the web system, usually refers to the user and the Web system dialogue process. This article will explain the contents of the session in detail

Session ID

In the history of Web technology, although the advent of cookie technology is a significant change, but the cookie is in the client computer to save information, so it caused a controversy. The user has the right to block the use of cookies so that the Web server cannot track user information through cookies. The session technology is to store user-related information in the server system, so users can not stop the use of the session

Session at the client only needs to save a session identifier created by the server for the user, called the session ID, and the value of the session variable is saved on the server side (file or database or memcache). Session ID is a string of 32-bit 16-digit numbers that are neither duplicated nor easily found.

The session ID is saved in the client's cookie, and if the user blocks the use of the cookie, the session ID can be saved in the URL of the user's browser address bar. When the user requests the Web server, the session ID is sent to the server, and then the session ID is extracted from the server in the session variable. The variables stored in the session can be considered as global variables for the user, and the same user's access to each script is shared.

When a user makes a request to a Web server, the server first checks to see if a session ID is already included in the client's request. If included, indicates that the session was previously created for this user, and the server is retrieved by the session ID for use. If the client request does not contain a session ID, a session is created for the user, and a session ID associated with the session is generated, which is passed to the client in this response to save

When a user makes a request to a Web server, the Session_Start () function must first be used to start a new session or to reuse an existing one, and a successful start session returns True, which returns false

BOOL Session_Start ([Array $options = []])

Because a cookie-based session is opened, calling the Session_Start () function generates a unique sessionid that needs to be stored in a cookie on the client computer, as in the Setcookie () function. Cannot have any output before the call, a space or a blank line.

If you have already opened the session, calling the Session_Start () function again will not create a new session ID. Because when the user accesses the server again, the function returns a session that already exists by passing the session ID that comes from the client. So during a session, the same user accesses any page on the server using the same session ID

Session_Start ();

Also, using the Session_Start () method creates a session file (a text file) with the same name on the server side.

If you do not want to use the Session_Start () function in each script to open the session, you can set the "Session.auto_start=1" in php.ini, you do not need to call session_start every time before using the session ( function However, there are some restrictions on enabling this option, and you cannot put the object in the session because the class definition must be loaded before the session starts. It is not recommended to use the Session.auto_start attribute in php.ini to open session

Read and write session

After the session is started using the Session_Start () method, the session is read and written by accessing the $_session array. Similar to $_post,$_get,$_cookie ,$_session is also a hyper-global array

Storing data in a SESSION file with the same name using the $_session array

<?phpsession_start (); $_session[' username '] = ' Huochai '; $_session[' age '] = 28;? >

The session file with the same name can be opened directly using a text editor with the following content structure:

Variable name | Type: Length: value;

<?phpsession_start ();p rint_r ($_session)//array ([username] + Huochai [age] =?>)

The session variable is saved in a file on the server side, where the file is located through the php.ini file, under the directory specified by the Session.save_path property

Configure session

In PHP configuration file php.ini, there is a set of session-related configuration options. By re-setting the new value for some options, you can configure the session or use the default session configuration

Phpinfo ();


session.auto_start=0; initialize sessionsession.cache_expire=180 at request startup; Set session document in cache obsolete session.cookie_lifetime=0 after n minutes; Set the cookie save time (s), equivalent to set the session expiration time, 0 indicates until the browser is restarted session.cookie_path=/;cookie valid path session.cookie_domain=; The valid domain session.name=phpsessid of a cookie; the name of the session used in the cookie session.save_handler=files; the control method for saving/retrieving data session.save_ path=/tmp; The parameter that is passed to the controller when the Save_handler is set to a file, which is the path to which the data file will be saved. Session.use_cookies=1; use of cookies

Destroy session

When you have finished using a session variable, you can delete it and destroy it when you have completed a conversation. If the user wants to quit the web system, it needs to provide a logout function to destroy all the information on the server. To destroy all the data related to the current session, you can call the Session_destroy () function to end the current session and empty all resources in the session

"Session_destroy ()"

BOOL Session_destroy (void)

Session_destroy () destroys all data in the current session, deletes the session file with the same name, but does not reset the global variables associated with the current session, nor resets the conversation cookie. If you need to use session variables again, you must recall the session_start () function

<?phpsession_start (); Session_destroy ();? >

You can use the unset () function to release a single variable registered in the session

Print_r ($_session);//' Array ([username] = Huochai [age] = +) ' unset ($_session[' username ']); unset ($_session[') Age ']);p rint_r ($_session);//' Array () '

[note] Do not use unset ($_session) to delete the entire $_session Array, so you can no longer register variables with the $_session Hyper-global array.

If you want to delete all the variables that a user registers in the SESSION, you can assign the array variable $_session to an empty array directly

$_session=array ();

PHP default session is based on the cookie, the session ID is stored in the client's cookie in the server, so in the logoff session also need to clear the cookie saved SessionID, and this must use Setcookie () function is complete. In a cookie, the cookie identifying name that holds the session ID is the name of the session, which is the value specified by the Session.name property in PHP.ini. In a PHP script, you can get the session name by calling the Session_name () function. Delete the session ID saved in the client cookie

if (Isset ($_cookie[session_name ()))) {        Setcookie (Session_name (), ", Time ()-3600);}

The previous introduction can be summed up, the session of the logoff process requires a total of four steps

<?php//First step: Open SESSION and Initialize session_start ();//second step: Delete all SESSION variables, also can be unset ($_session[xxx]) Delete $_session = Array () ;///Step three: If using a COOKIE-based session, use Setcooike () to delete the Cookieif (Isset ($_cookie[session_name ()) containing the session ID {    Setcookie (Session_name (), ", Time ()-42000);} Fourth step: Finally completely destroy the session, delete the server side retention session information file Session_destroy ();? >

Automatic Recycling

If you do not destroy the session through the above steps, but instead directly close the browser, or off the network, etc., the session file saved on the server will not be deleted. Because in the php.ini configuration file, the default session.cookie_lifetime=0 indicates that the session ID is valid for the client cookie until the browser is closed. The session ID disappears, but the session file saved by the server is not deleted. Therefore, the server-side session file that is not associated with the session ID becomes garbage, and the system provides a mechanism for automatic cleanup.

The session file saved by the server is a normal text file with file modification time. Set an expiration time by setting the Session.gc_maxlifetime option in the php.ini configuration file (default is 1440 seconds, or 24 minutes). The garbage collection program finds files in all session files that are larger than 24 minutes. If the user is still using the file, then the session file modification time will be updated, will not be detected

When excluded, the garbage is not cleaned up immediately, but is determined by the ratio of the session.gc_probability/session.gc_pisor values in the profile php.info to when the cleanup is made, the default value is 1/100. Indicates that the garbage collection mechanism may be started at one time to automatically recycle garbage after 100 troubleshooting. Of course, this value can be modified, but also to take into account the performance of the server and storage space

Pass Session

Using the session to track a user, is to pass a unique session ID between each page, and through the session ID to extract the user in the server saved session variables. The following two types of session ID transfer methods are common

1. Pass the session ID in a cookie-based manner. This approach is more optimized, but because it is not always available, users can block cookies on the client

2, pass the URL parameter, directly embed the session ID into the URL

In the implementation of the session is usually a cookie-based approach, the client saves the session ID is a cookie. When the customer disables the cookie, the session ID can no longer be saved in the cookie, and it cannot be passed between pages, at which time the session expires. However, the PHP5 can automatically check the cookie status on the Linux platform, and if the client disables it, the system automatically attaches the session ID to the URL for delivery. The use of Windows systems as a Web server does not have this feature

"Pass the session ID via a cookie"

If the client does not disable cookies, the server automatically sends an HTTP header to save the session ID to the client computer's cookie after initializing it in the PHP script via the session_start () function.
Similar to the following setting method

The process of setting the session ID in a virtual cookie Setcookie (Session_name (), session_id (), 0, '/')

The first parameter calls the Session_name () function, which returns the name of the current session as the identity name of the cookie. The default value for session name is PHPSESSID, which is the value specified by the Session.name option in the php.ini file. You can also change the name of the current session by providing a parameter when calling the Session_name () function

Echo Session_name ();//phpsessid

The second parameter calls the session_id () function, which returns the current session ID as the value of the cookie. You can also set the current session ID by calling the session_id () function when you provide the parameter

Echo session_id ();//kstvdmae177qqk6jgvg6td12l1

The value of the third parameter, 0, is the value set by the Session.cookiejifetime option in the php.ini file. The default value is 0, which means that the session ID will continue in the client's cookie until the browser is closed

The last parameter, '/', is also the value set by the Session.cookie.path option in php.ini by the value specified by the PHP configuration file. The default value is '/', indicating that the path to be set in the cookie is valid throughout the domain

If the server succeeds in saving the session ID in the client's cookie, the session ID will be sent back when the user requests the server again. So when the Session_Start () function is used again in the script, it returns the existing session based on the session ID in the cookie.

"Pass the session ID by URL"

If the customer's browser supports cookies, the session ID is stored in the browser as a cookie. However, if the client prohibits the use of cookies, there is no session ID in the browser as a cookie, so cookie information is not included in the customer request. If the session_start () function is called and the session ID of the cookie cannot be obtained from the client browser, a new session ID is created and the customer status cannot be traced. Therefore, each time a client requests a PHP script that supports session, the Session_Start () function creates a new session when the session is opened, thus losing the ability to track user state.

If the client browser does not support cookie,php, you can rewrite the URL of the client request and add the session ID to the URL information. You can manually add a session ID to the URL of each hyperlink, but the workload is relatively large, and is not recommended in this way. As shown below:

<?php    session_start ();    Echo ' <a href= ' demo.php? '. Session_name (). ' = '. session_id (). ' " > link demo </a> ';? >

When using the Linux system as a server, and choose PHP4.2 later version, when editing PHP if the-ENABLE-TRANS-SID configuration option is used, and the runtime option Session.use_trans_sid is activated, When a cookie is disabled by the client, the relative URL is automatically modified to contain the session ID. If this is not configured, or if you are using a Windows system as a server, you can use a constant SID. The constant is defined when the session is started, and if the client does not send the appropriate session cookie, the SID is in the format session_name=session_id, or an empty string. Therefore, it can be unconditionally embedded into the URL. As shown below

When a cookie is blocked, the SID returns ' Phpsessid=p2qouo8hjarul0a0ii5jmocmc0 ', otherwise an empty string echo SID is returned;
<?php    session_start ();     $_session["Usemame"]= "admin";     echo "Session ID:". session_id (). " <br> ";? ><a href= "test2.php?<?php echo SID?>" > Pass the session via URL id</a>

If you use a Linux system as a server and configure the appropriate options, you do not have to manually append a SID to each URL, and the relative URL will be automatically modified to include the session ID. Note, however, that a non-relative URL is assumed to point to an external site and therefore cannot attach a SID. Because this can be a security risk, the SID is compromised to a different server

Custom session

When using session technology to track a user in the system, the session is handled by default by using the files in the Web server to record the session information for each user, creating the path to the session data file through Session_save_path in php.ini. This default approach, although convenient, has some drawbacks. For example, if the logged-on user is very large, the I/O overhead of file operations can be significant and can seriously affect the execution efficiency of the system. In addition, the main thing is that its own session mechanism can not be cross-machine, because for a large number of access to the system, usually using multiple Web servers for concurrent processing, if each Web server is separate processing session, it is impossible to track the user's purpose. At this point, we need to change the processing of the session, the common cross-machine method is through the custom session storage, you can use the session information using NFS or samba and other sharing technology to save to other servers, or use a database to save session information, The best way is to use memcached for session storage

Sharing session information with memcached, the database, or via NFS or samba is the same principle, with the Session_set_save_handler () function in PHP changing the default processing mode. Specifies the callback function to customize the processing

Session_set_save_hander (callback Open,callback close,call read,callback write,callback destro,callback GC);

The function requires 6 callback functions as required parameters, which represent 6 processes in the session life cycle, and the user can customize each function to set the information processing of each session in the session life cycle.

The execution time of the callback function is as follows

 The callback function describes the Open run Session_Start () execution, the function needs to declare two parameters, the system automatically php.ini The Ave_path option value is passed to the first argument of the function, the session name is passed to the second argument automatically, and true can continue to execute down close. The function does not require arguments when the script executes or calls Session_write_close (), Session_destroy () is executed when all session operations are completed. If no processing is required, the direct return of true allows read to run session_start () when the session is opened and the current session data is read and the $_session variable is written. Need to declare a parameter, the system will automatically pass the session ID to the function, to get the corresponding user data through session ID, return the current user's session information to write the $_session variable writes the function at the end of the script and the $_session variable assignment data Yes. You need to declare two parameters, namely session ID and serialization session information string. When assigning a value to a $_session variable, the stored location can be found through the session ID and the information is written. Store success can return true to continue execution down destroy when running Session_destroy (), need to declare a parameter, the system will automatically pass the session ID to the function, to delete the corresponding sessions information GC garbage collector starts Yes. To declare a parameter, the system automatically passes the value of the Session_gc_maxlifetime option in php.ini to the function to delete the session information that exceeds that time, and returns true to continue execution down 

The open (Start session), read (reading session data to $_session), and GC (garbage cleanup) were executed separately when Session_Start () was run, and all of the scripts were $_session Do not call these callback functions. When the Session_destroy () function is called, execution destroy destroys the current session (typically deleting the corresponding record or file), but the callback function destroys only the session data, at which point the output $_session variable, There are still values, but this value will not be written back after close. Write and close are executed when the Session_write_close () function is called, save $_session to storage, and if this method is not used manually, it will be executed automatically at the end of the script

[Note the]session_set_save_hander () function must be set in php.ini when the value of the Session_save_hander option is "User" (custom processor) before it is called by the system

<?php $sess _save_path = "";         function open ($save _path, $session _name) {global $sess _save_path;                $sess _save_path = $save _path;     return true;     } function Close () {return true;          } function Read ($id) {global $sess _save_path;         $sess _file = "{$sess _save_path}/sess_{$id}";     Return (String) @file_get_contents ($sess _file);          } function Write ($id, $sess _data) {global $sess _save_path;         $sess _file = "{$sess _save_path}/sess_{$id}";                        if ($fp = @fopen ($sess _file, "W")) {$return = Fwrite ($fp, $sess _data);             Fclose ($FP);         return $return;         }else{return false;          }} function Destroy ($id) {global $sess _save_path;         $sess _file = "{$sess _save_path}/sess_{$id}";     Return (@unlink ($sess _file));             } function GC ($maxlifetime) {global $sess _save_path; foreach (Glob ("{$sess _save_path}/sess_* ") as $filename) {if (Filemtime ($filename) + $maxlifetime <time ()) {             @unlink ($filename);     }} return true;    } session_set_save_hander ("Open", "close", "read", "write", "Destroy", "GC"); Session_Start ();? >

Database processing

If the Web site access is very large, you need to use load balancing technology to carry multiple Web servers to work together, you need to perform session synchronization. Using a database to process a session is more advantageous than using NFS and samba, and it is possible to set up a database server to hold the session information of the Web server, which will go to this specialized database regardless of which Web server is accessed in the cluster. Access the session information stored on the server side to achieve the purpose of session synchronization. In addition, the use of database processing session can also bring us a lot of benefits, such as statistics on the number of people online. If MySQL also does a cluster, each MySQL node must have this table, and this session table data to synchronize in real time

When using the default file method to process the session, there are 3 more important properties, namely the file name, file content and file modification time: Through the file name contains the session ID, users can find their own server-side session file Through the file content the user can access the $_session variable in each script, and the modified time of the file can erase all expired session files. So use the data table to process Session information, and at least three fields (session ID, modification time, session content information), of course, if you consider more cases, for example, the user changed the IP address, the user switched the browser, etc., you can also customize some other fields. The following data table structure for the session contains 5 fields, and the SQL statement that holds the session information table is as follows:

CREATE TABLE session (    Sid char (+) NOT null default ",    update INT NOT NULL default 0,    client_ip char () Null default ',    user_agent CHAR ($) Not NULL default ' ',    data TEXT,    PRIMARY KEY (SID));

After the

Data table session is created successfully, the session information is written to the database through a custom processing method

<?phpclass dbsession {public static $pdo;           The object public of the PDO is static $ctime;     The current time public static $maxlifetime;             Maximum time to live public static $uip;          The user is using the IP public static $uagent;        User is using the browser//open and the initial use, parameters need a road public static function start (PDO $pdo) {self:: $pdo = $pdo;        Self:: $ctime = time ();        Self:: $maxlifetime = Ini_get ("Session.gc_maxlifetime"); Self:: $uip =!empty ($_server[' http_client_ip '))? $_server[' http_client_ip ': (!empty ($_server[' http_x_forwarded_for '])? $_server[' Http_x_forwarded_for ']: (!empty ( $_server[' REMOTE_ADDR ')?        $_server[' REMOTE_ADDR ']: ");        Filter_var (self:: $uip, Filter_validate_ip) && self:: $uip = '; Self:: $uagent =!empty ($_server[' http_user_agent '))?        $_server[' Http_user_agent ']: ""; The registration process allows PHP to handle the session itself, looking for several cycles specified by this function to complete the Session_set_save_handler (array (CLASS, "open"), arr Ay (CLASS, "close"),           Array (class, "read"), Array (class, "write"), Array (class, "destroy"), Array (        CLASS, "GC"));  Session_Start ();    Open Session}//On, session_start () public static function open ($path, $name) {return true;    }//Close public static function close () {return true; }//Read echo $_session[' username ' public static function read ($SID) {$sql = "select * from SESSION where s        id =? ";        $stmt = self:: $pdo-Prepare ($sql);        Execute (Array ($SID), $stmt);        $result = Fetch (PDO::FETCH_ASSOC) $stmt;        If no session information is available, return an empty string if (! $result) {return '; }//If time is exceeded, destroy session if ($result [' utime '] + self:: $maxlifetime < self:: $ctime) {self::d Estroy (            $SID);        Return '; }//If the user changed the IP or changed the browser if ($result [' uip ']! = Self:: $uip | | $result [' uagent ']! = Self:: $uagent) {self:            :d Estroy ($SID); RetUrn ";    } return $result [' sdata '];    }//write $_session[' username '] = "Meizi";        public static function Write ($sid, $data) {//Gets the data already available through the SID $sql = "SELECT * from session where SID =?";        $stmt = self:: $pdo->prepare ($sql);        Execute (Array ($SID), $stmt);                $result = Fetch (PDO::FETCH_ASSOC) $stmt; If the data has been obtained, do not insert and update if ($result) {//If the data and the original are different before updating if ($result [' sdata ']! = $data | | $result [' u Time ']+10 < self:: $ctime) {$sql = "Update session set Sdata =?, Utime =?                where sid=? ";                $stmt = self:: $pdo->prepare ($sql);            $stmt, execute (Array ($data, self:: $ctime, $sid)); }//If there is no data, insert a new data} else {if (!empty ($data)) {$sql = "INSERT INTO Sessi                On (SID, Sdata, Utime, UIP, uagent) VALUES (?,?,?,?,?) ";                $stmt = self:: $pdo-Prepare ($sql); $stmt Execute (Array ($SID, $data, Self:: $ctime, Self:: $uip, Self:: $uagent)); }}}//Destroy Session_destroy () public static function Destroy ($SID) {$sql = "Delete from session W        Here sid=? ";        $stmt = self:: $pdo->prepare ($sql);     Return $stmt, execute (Array ($SID));  }//Recycle garbage public static function GC ($MAXLIFETIME) {//Utime < ctime-self:: $maxlifetime $sql =        "Delete from session where Utime <?";        $stmt = self:: $pdo->prepare ($sql);         Return $stmt, execute (Array (self:: $ctime-self:: $maxlifetime)); }}//Open Dbsession::start ($PDO);

memcached processing

Synchronizing a session with a database can increase the burden on the database, since the database is inherently prone to bottlenecks, but it is appropriate to use memcache to process sessions because the Memcache cache mechanism is very similar to the session. In addition, Memcach can be distributed, able to combine the memory of the Web server into a "memory pool", regardless of which server generated the session, can be placed in the "Memory Pool", other Web servers can be used. Synchronizing sessions in this way does not increase the burden on the database and is more secure than using cookies. Put the session into memory and read it much faster than any other processing method.

Customizing processing session information using memcached is the same as customizing the database, but much simpler, because Memcache works in a similar way to session technology

<?phpclass memsession {public static $mem;     The object public of the PDO is static $maxlifetime;            Maximum time to live public static function start (Memcache $mem) {self:: $mem = $mem;            Self:: $maxlifetime = Ini_get ("Session.gc_maxlifetime"); The registration process allows PHP to process the session itself, following the period specified by this function to complete the Session_set_save_handler (array (CLASS, "open"), AR Ray (class, "close"), Array (class, "read"), Array (class, "write"), Array (class, "destroy")        , Array (CLASS, "GC"));  Session_Start ();    Open Session}//On, session_start () public static function open ($path, $name) {return true;    }//Close public static function close () {return true;        }//Read echo $_session[' username ' public static function read ($SID) {$data = self:: $mem, Get ($SID);        if (empty ($data)) {return ';    } return $data; }//write public static function write ($Sid, $data) {self:: $mem-Set ($sid, $data, memcache_compressed, Self:: $maxlifetime);    }//Destroy Session_destroy () public static function Destroy ($SID) {self:: $mem, delete ($sid, 0);        }//Recycle garbage public static function GC ($maxlifetime) {return true;    }}//create object $mem = new Memcache ();    Add two memcache server $mem-addserver ("localhost", 11211);    $mem-Addserver ("192.168.1.3", 11211); Open Memsession::start ($MEM);? >
Related Article

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.