This article describes in detail the use of session in php, a good example to help you learn, easy to understand. Previous
Session technology is similar to Cookie technology, and is used to store user-related information. But the biggest difference is that the Cookie stores data in the client computer, while the Session stores the data under the server system. The Chinese meaning of a Session is a Session. in a Web system, a Session usually refers to a conversation between a user and a Web system. This topic describes the Session details.
Session ID
In the history of Web technology development, although the emergence of Cookie technology is a major change, Cookie stores data in the client computer, which has aroused a controversy. The user has the right to prevent the use of cookies, so that the Web server cannot track user information through cookies. The Session technology stores user-related data in the server system, so users cannot stop using sessions.
The Session only needs to save a Session identifier created by the server for the user on the client, called the Session ID. the Session variable value is saved on the server side (in files, databases, or MemCache. Session ID is a string consisting of 32-bit hexadecimal numbers that is neither repeated nor easily discovered.
If you do not want to use the Session_start () function in each script to enable the Session, you can. set "session. auto_start = 1 ", you do not need to call the session_start () function every time before using the Session. However, if this option is enabled, objects cannot be put into the Session because the class definition must be loaded before the Session is started. Therefore, we do not recommend that you use the session. auto_start attribute in php. ini to enable the Session.
Read/write session
After you start a session using session_start (), you need to access the $ _ SESSION array to read and write sessions. Similar to $ _ POST, $ _ GET, and $ _ COOKIE, $ _ SESSION is an ultra-global array.
Use the $ _ SESSION array to save data to a Session file with the same name
A Session file with the same name can be opened directly in a text editor. the content structure of the file is as follows:
Variable name | type: Length: value;
huochai [age] => 28 )?>
Session variables are stored in a file on the server. the file is stored in the directory specified by the session. save_path attribute through the php. ini file.
Configure Session
In the PHP configuration file php. ini, there is a set of Session-related configuration options. You can configure the Session by resetting the new value for some options. Otherwise, the default Session configuration is used.
phpinfo();
Session. auto_start = 0; the sessionsession is initialized when the request starts. cache_expire = 180; set the session document in the cache to expire after n minutes. cookie_lifetime = 0; setting the cookie retention time (s) is equivalent to setting the Session expiration time. if it is set to 0, it indicates that the session is restarted in the browser. cookie_path =/; the valid cookie path session. cookie_domain =; cookie's valid domain session. name = PHPSESSID; name of the session used in the cookie session. save_handler = files; the session used to save/retrieve data. save_path =/tmp; the parameter that is passed to the controller when save_handler is set to a file. this is the path where the data file will be saved. session. use_cookies = 1; whether to use cookies
Destroy Session
After a Session variable is used, it can be deleted. after a Session is completed, it can also be destroyed. If you want to exit the Web system, you need to provide a logout Function to destroy all information on the server. To destroy all information related to the current Session, you can call the session_destroy () function to end the current Session and clear all resources in the Session.
[Session_destroy ()]
bool session_destroy ( void )
Session_destroy () destroys all data in the current Session and deletes the Session file of the same name. However, it does not reset the global variables associated with the current Session, nor reset the Session cookie. To use the session variable again, you must call the session_start () function again.
You can use the unset () function to release a single variable registered in the Session.
print_r ($_SESSION);//'Array ( [username] => huochai [age] => 28 )'unset($_SESSION['username']);unset($_SESSION['age']);print_r ($_SESSION);//'Array()'
[Note] do not use unset ($ _ SESSION) to delete the entire $ _ SESSION array. in this way, variables cannot be registered through the $ _ SESSION over the global array.
If you want to delete all the variables registered by a user in the Session, you can directly assign the $ _ SESSION variable to an empty array.
$_SESSION=array();
The default Session in PHP is Cookie-based. the Session ID is stored by the server in the Cookie of the client. Therefore, you must clear the SessionID stored in the Cookie when canceling the Session, this must be done using the setCookie () function. In the Cookie, the Cookie ID that stores the Session ID is the name of the Session, which is the value specified by the session. name attribute in php. ini. In a PHP script, you can call the session_name () function to obtain the Session name. Delete the Session ID stored in the client Cookie
if(isset($_COOKIE[session_name()])) { setCookie(session_name(),'',time()-3600);}
We can conclude from the previous introduction that the cancellation process of the Session requires four steps.
Automatic Recovery
If the Session is not destroyed through the above steps, but the browser is closed directly, or the network is disconnected, the Session files saved on the server will not be deleted. In the php. ini configuration file, the default session. cookie_lifetime = 0 indicates that the Session ID is valid on the client Cookie until the browser is closed. The Session ID disappears, but the Session file saved on the server is not deleted. Therefore, the server-side Session file not associated with the Session ID becomes junk, and the system provides an automatic cleaning mechanism.
The Session files stored on the server are common text files with modification time. Set the session. gc_maxlifetime option in the php. ini configuration file to set an expiration time (1440 seconds by default, that is, 24 minutes ). The garbage collection program sorts out all Session files for more than 24 minutes. If the user is still using this file, the modification time of this Session file will be updated and will not be found
After it is excluded, it does not immediately clean up the garbage. Instead, it determines when to clean up based on the ratio of session. gc_probability/session. gc_pisor values in the configuration file php.info. the default value is 1/100. Indicates that the garbage collection mechanism may be enabled only once after 100 troubleshooting. Of course, this value can be modified, but it must take into account the running performance and storage space of the server.
Transfer session
A Session is used to track a user by passing a unique Session ID between pages and extracting the Session variable that the user saves on the server through the Session ID. Common Session ID transfer methods are as follows:
1. pass the Session ID in Cookie-based mode. This method is more optimized, but it is not always available because users can block cookies on the client.
2. pass the URL parameter and embed the session ID directly into the URL.
Generally, Session implementation uses Cookie-based methods. The Session ID stored by the client is a Cookie. When a customer disables a Cookie, the Session ID cannot be saved in the Cookie, and cannot be transferred between pages. in this case, the Session becomes invalid. However, on the Linux platform, PHP5 can automatically check the Cookie status. if the client disables it, the system automatically attaches the Session ID to the URL for transmission. This function is not available when Windows is used as a Web server.
[Pass Session ID through Cookie]
If no Cookie is disabled on the client, the server automatically sends an HTTP header to save the Session ID to the Cookie on the client after initialization by using the session_start () function in the PHP script.
Similar to the following setting method
// Set the Session ID in the virtual Cookie process setCookie (session_name (), session_id (), 0 ,'/')
The first parameter calls the session_name () function and returns the name of the current Session as the Cookie identifier. The default value of the Session name is PHPSESSID, which is the value specified by the session. name option in the php. ini file. You can also provide a parameter to change the name of the current Session when calling the session_name () function.
echo session_name();//PHPSESSID
The second parameter calls the session_id () function and returns the current Session ID as the Cookie value. You can also set the current Session ID by providing parameters when calling the session_id () function.
echo session_id();//kstvdmae177qqk6jgvg6td12l1
The value 0 of the third parameter is set by the session. cookiejifetime option in the php. ini file. The default value is 0, indicating that the SessIon ID will be extended to the browser in the Cookie of the client.
The last parameter '/' is also the value specified by the PHP configuration file, which is set by the session. cookie. path option in php. ini. The default value is '/', indicating that the path to be set in the Cookie is valid throughout the domain.
If the server successfully saves the Session ID in the Cookie of the client, the Session ID will be sent back when the user requests the server again. Therefore, when the session_start () function is used again in the script, an existing Session is returned based on the Session ID in the Cookie.
[Pass Session ID through URL]
If your browser supports cookies, save the Session ID as a Cookie in your browser. However, if the client prohibits the use of cookies, the browser does not have a Session ID that serves as a Cookie. Therefore, the client request does not contain Cookie information. If the Session ID of the Cookie cannot be obtained from the client browser when the session_start () function is called, a new Session ID is created, and the customer status cannot be tracked. Therefore, each time the customer requests a PHP script that supports the Session, the session_start () function creates a new Session when the Session is enabled, thus losing the function of tracking the user status.
If the client browser does not support cookies, PHP can rewrite the client request URL 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 heavy. We do not recommend this method. As follows:
When using the Linux system as the server and using PHP4.2 or later versions, if the-enable-trans-sid configuration option is used during PHP editing, and the runtime option session is used. use_trans_sid is activated. When Cookie is disabled on the client, the relative URL is automatically changed to include Session ID. If this configuration is not configured, or you use Windows as the server, you can use the constant SID. This constant is defined at session startup. if the client does not send an appropriate session Cookie, the SID format is session_name = session_id; otherwise, it is an empty string. Therefore, it can be embedded in the URL unconditionally. As shown below
// When the cookie is blocked, SID returns 'phpsessid = p2qouo8hjarul0a0ii5jmocmc0'; otherwise, an empty string echo SID is returned;
";?> "> Pass Session ID through URL
If you use Linux as the server and configure the corresponding options, you do not need to manually append the SID to each URL. the relative URL will be automatically changed to include the Session ID. However, it should be noted that non-relative URLs are assumed to point to external sites, so SID cannot be appended. This may be a security risk and may expose the SID to different servers.
Custom Session
When the Session technology is used in the system to track users, the default Session processing method is to use files on the Web server to record the Session information of each user. session_save_path in ini to create the path of the session data file. This default processing method is convenient, but it also has some defects. For example, if a login user is very large, the I/O overhead of file operations will be very large, which will seriously affect the system execution efficiency. In addition, the most important thing is that its session mechanism cannot be cross-host, because for systems with a large access volume, multiple web servers are usually used for concurrent processing, if each web server processes sessions independently, it is impossible to track users. In this case, you need to change the session processing method. the common cross-host method is to store session information to other servers using NFS or SAMBA sharing technologies, or use a database to store session information. the optimal method is to use memcached for session storage.
Whether memcached, database, or NFS or SAMBA is used to share session information, the principle is the same. the default processing method is changed through the session_set_save_handler () function in PHP, specify callback function for custom processing
Session_set_save_hander(callback open,callback close,call read,callback write,callback destro,callback gc);
This function requires six callback functions as required parameters, representing the six processes in the Session lifecycle. you can customize each function, to set information processing for each link in the Session lifecycle.
The execution time of the callback function is as follows:
The callback function description is executed when session_start () is run in open mode. this function requires two parameters to be declared. in ini, the session_save_path option value is passed to the first parameter of the function, and the Session name is automatically passed to the second parameter. if true is returned, you can continue to execute the close operation downward without parameters, when the script execution is complete or session_write_close () and session_destroy () are called, it is executed after all session operations are completed. If no processing is required, return true directly to run session_start (), because when the session is enabled, the current SESSION data is read and the $ _ session variable is written. If a parameter needs to be declared, the system will automatically pass the Session ID to the function to obtain the corresponding user data through the Session ID, returns the current user's SESSION information and writes $ _ SESSION variable write. This function is executed at the end of the script and when the $ _ SESSION variable is assigned a value. Two parameters need to be declared, namely the Session ID and the serialized Session information string. When assigning values to the $ _ SESSION variable, you can use the Session ID to locate the storage location and write the information. If the storage succeeds, you can return true and continue to run destroy to run session_destroy (). If you need to declare a parameter, the system will automatically pass the Session ID to the function, delete the corresponding session information. The gc garbage collection program is executed at startup. You need to declare a parameter. The system will automatically pass the session_gc_maxlifetime option value in php. ini to this function to delete the Session information that exceeds this time. if true is returned, you can continue to execute
When session_start () is run, open (start session), read (read SESSION data to $ _ session), and gc (clean up garbage) are executed, respectively ), all operations on $ _ SESSION in the script do not call these callback functions. When the session_destroy () function is called, run destroy to destroy the current session (usually to delete the corresponding records or files). However, this callback function only destroys the Session data, at this time, if the $ _ SESSION variable is output, there is still a value, but this value will not be closed and then written back. Execute write and close when calling the session_write_close () function, and save $ _ SESSION to storage. if you do not use this method manually, it will be automatically executed when the script ends.
[Note] the session_set_save_hander () function must be called by the system only when the session_save_hander option value is set to "user" in php. ini.
Database Processing
If the website traffic is very large, you need to use the server load balancer technology to carry out multiple Web servers to work collaboratively, you need to perform Session synchronization. Session processing using a database is more dominant than using NFS and SAMBA. you can create a database server to store Session information of the Web server. when a user accesses any Web server in the cluster, all of them will go to this dedicated database to access the Session information stored on the server side to achieve Session synchronization. In addition, using a database to process sessions can bring us many benefits, such as counting the number of online users. If mysql is also a cluster, each mysql node must have this table and the data in this Session table must be synchronized in real time.
When the default file method is used to process sessions, there are three important attributes: file name, file content, and File Modification time: the Session ID contained in the file name, users can find their own Session files on the server side. through the file content, users can access the $ _ session variable in each script. through the modification time of the file, all expired Session files can be cleared. Therefore, when you use a data table to process Session information, you must have at least these three fields (Session ID, modification time, and Session content). of course, if you consider more situations, such, the user has changed the IP address, switched the browser, and other fields. The data table structure designed for the Session contains five Fields. the SQL statement for creating and saving the Session information table is as follows:
CREATE TABLE session( sid CHAR(32) NOT NULL DEFAULT '', update INT NOT NULL DEFAULT 0, client_ip CHAR(15) NOT NULL DEFAULT '', user_agent CHAR(200) NOT NULL DEFAULT '', data TEXT, PRIMARY KEY(sid));
After the data table session is created successfully, the Session information is written to the database in a custom processing method.
Prepare ($ SQL); $ stmt-> execute (array ($ sid); $ result = $ stmt-> fetch (PDO: FETCH_ASSOC ); // if no session information exists, an empty string if (! $ Result) {return '';} // if the time limit is exceeded, destroy the session if ($ result ['utime'] + self: $ maxlifetime <self: $ ctime) {self: destroy ($ sid); return '';} // if the user changes the ip address or the browser if ($ result ['uip']! = Self: $ uip | $ result ['uagent']! = Self ::$ uagent) {self: destroy ($ sid); return '';} return $ result ['sdata'];} // write $ _ SESSION ['username'] = "meizi"; public static function write ($ sid, $ data) {// Obtain existing data through sid $ SQL = "select * from session where sid =? "; $ Stmt = self: $ pdo-> prepare ($ SQL); $ stmt-> execute (array ($ sid )); $ result = $ stmt-> fetch (PDO: FETCH_ASSOC); // if the data has been obtained, update if ($ result) without inserting it) {// if the data is different from the original one, update if ($ result ['sdata']! = $ Data | $ result ['utime'] + 10 <self: $ ctime) {$ SQL = "update session set sdata = ?, Utime =? Where sid =? "; $ Stmt = self: $ pdo-> prepare ($ SQL); $ stmt-> execute (array ($ data, self: $ ctime, $ sid);} // if no data exists, insert a new data record.} else {if (! Empty ($ data) {$ SQL = "insert into session (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 where sid =? "; $ Stmt = self: $ pdo-> prepare ($ SQL); return $ stmt-> execute (array ($ sid ));} // collect 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) ;}}// start DBSession: start ($ pdo );
Memcached processing
Using a database to synchronize sessions will increase the burden on the database, because the database is prone to bottlenecks, but it is very appropriate to use MemCache to process sessions, because MemCache's Cache mechanism is very similar to Session. In addition, MemCach can be distributed and can combine the memory in the Web server into a "memory pool". no matter which server generates the Session, it can be placed in this "memory pool, other Web servers can be used. In this way, Session synchronization will not increase the burden on the database, and the security is higher than that of using cookies. Put the session in the memory and read it much faster than other processing methods.
Custom memcached is used to process session information, which is the same as that of a custom database. However, memcached is much simpler because its working mechanism is similar to Session technology.
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 an object $ mem = new Memcache (); // add two memcache servers $ mem-> ad DServer ("localhost", 11211); $ mem-> addServer ("192.168.1.3", 11211); // enable MemSession: start ($ mem);?>
The above is the detailed content of the Session for the frontend to learn PHP. For more information, see other related articles in the first PHP community!