In-depth explanation of PHPSession and how to keep it from expiration

Source: Internet
Author: User
Tags echo date php session
This article mainly introduces the PHPSession and how to keep it from expiration, including the explanation of the Session recycling mechanism and the solution to the problem that SessionId remains unchanged, if you need a SESSION, refer to the COOKIE technology used in the implementation of the SESSION. The SESSION will save a COOKIE containing session_id (session number) on the client, and save other SESSION variables on the server, for example, session_name. When a user requests a server, the session_id is also sent to the server. the session_id is used to extract the variables stored on the server to identify who the user is. At the same time, it is not difficult to understand why the SESSION sometimes fails.

When the client disables cookies (click "tools"-"Internet options" in IE, and click "security"-"custom level" in the pop-up dialog box, set "allow COOKIE for each conversation" to disabled). session_id cannot be passed, and the SESSION becomes invalid. However, php5 can automatically check the cookie status on linux/unix platforms. if the client is disabled, the system automatically attaches session_id to the url for transmission. Windows host does not have this function.

Common Session functions and usage?
Session_start (): start a session or return an existing session.
Note: This function has no parameters and returns true. If you use cookie-based sessions, the browser cannot output any output before Session_start (). Otherwise, the following error occurs:
Warning: Cannot send session cache limiter-headers already sent (output started at/usr/local/apache/htdocs/cga/member/1.php: 2 )............


You can start session. auto_start = 1 in php. ini, so you do not need to call session_start () every time before using the session (). However, enabling this option also has some restrictions. if the session is enabled. auto_start, the object cannot be put into the session, because the class definition must be loaded before the session is started to recreate the object in the session.
All registered variables are serialized after the request ends. Registered but undefined variables are marked as undefined. In subsequent access, these variables are not defined by the session module unless you define them later.

Warning some types of data cannot be serialized and therefore cannot be stored in sessions. Including resource variables or objects with circular references (that is, an object passes a reference pointing to itself to another object ).

Register SESSION variables:
PHP5 registers the SESSION global variable with $ _ SESSION ['XXX'] = xxx. Similar to GET, POST, and COOKIE usage.
Note: session_register (), session_unregister, and session_is_registered are no longer used in php5 unless register_globle is set to on in php. ini. However, it is strongly recommended to disable register_globle for security reasons. HTTP_SESSION_VARS is not recommended. we recommend that you use $ _ SESSION instead. For example:

Page1.php

<? Php Session_start (); // This function must be called before SESSION is used. $ _ SESSION ['name'] = "I am a black tornado Li Yun !"; // Register a SESSION variable $ _ SESSION ['passwd'] = "mynameislikui"; $ _ SESSION ['Time'] = time (); echo 'pass SESSION through cookies '; // if the client supports cookies, the session can be passed to the next page through this link. Echo '. SID.' "> pass SESSION through URL '; // when the client does not support cookie, use this method to pass session.?>

Page2.php

<? Php session_start (); echo $ _ SESSION ['name']; // echo $ _ SESSION ['passwd']; // echo date ('Y m d H: I: s ', $ _ SESSION ['Time']); echo 'back to a mountain page';?>

There are two ways to pass a Session ID:

  1. Cookie
  2. URL parameters

The session module supports these two methods. Cookies are more optimized, but they are not always available and provide alternative methods. The second method directly embeds the session ID in the middle of the URL.

PHP can transparently convert the connection. Unless PHP 4.2 or later is used, it needs to be activated when PHP is compiled manually. In Unix, use -- enable-trans-sid to configure options. If this configuration option and the runtime option session. use_trans_sid are activated (modify php. ini), the URI will be automatically changed to include session ID.

Session_id
Session_id () is used to set or obtain the current session_id. In php5, you can use session_id () or get the session_id and session_name of the current session by the SID appended to the url.
If session_id () has a specific value, it will replace the current session_id value. Before using this function, you must start the session: session_start ();
When session cookies are used, if a session_id () value is specified, each time session_start () is started, a cookie value will be sent to the client. Whether or not the current session_id is equal to the specified value.
If no value is specified for session_id (), the current session_id () is returned. if the current session is not started, an empty string is returned.

Check whether the session exists?
In previous php versions, session_is_register () is used to check whether a session exists. if you use $ _ SESSION ['XXX'] = XXX to register a session variable, session_is_register () function no longer works. You can use
Isset ($ _ SESSION ['XXX.

If session_id session_regenerate_id () is changed successfully, true is returned. if it fails, false is returned.
This function can be used to change the session_id of the current session, but does not change other information of the current session. For example:

<? Php session_start (); $ old_sessionid = session_id (); session_regenerate_id (); $ new_sessionid = session_id (); echo "original SessionID: $ old_sessionid"; echo "new SessionID: $ new_sessionid "; echo" "; print_r ($ _ SESSION); echo" ";?>

Session_name () returns the name of the current session or changes the name of the current session. To change the name of the current session, you must call this function before session_start. Note: session_name cannot be composed of only numbers. it must contain at least one letter. Otherwise, a new session id will be generated every moment.
Session renaming example:

$ Previus_name = session_name ("WebsiteID"); echo "New session name: $ previous_name";?>

How to delete a session?
1. unset ($ _ SESSION ['XXX']) deletes a single session. unset ($ _ SESSION ['XXX']) is used to unregister a registered session variable. It works the same as session_unregister. Session_unregister () is no longer used in PHP5 and can be used in the cold Palace.
Unset ($ _ SESSION) is not available. it destroys the global variable $ _ SESSION and there is no feasible way to restore it. You can no longer register the $ _ SESSION variable.
2. $ _ SESSION = array () delete multiple sessions
3. session_destroy () ends the current session and clears all resources in the session .. This function does not unset (release) the global variables related to the current session, nor delete the client session cookie. the default session of PHP is cookie-based. to delete a cookie, you must use the setcookie () function.
Return value: Boolean value.
Function description: This function ends the current session. this function has no parameters and returns true.

Session_unset () if $ _ SESSION is used, this function no longer works. Since PHP 5 must use $ _ SESSION, this function can be used in the cold room.

The following is an official PHP case concerning session deletion:

<? Php // initialize session. session_start ();/*** delete all session variables .. unset ($ _ SESSION [xxx]) can also be deleted one by one. * ***/$ _ SESSION = array ();/*** delete sessin id. because the session is cookie-based by default, setcookie is used to delete the cookie containing the session id. * **/if (isset ($ _ COOKIE [session_name ()]) {setcookie (session_name (), '', time ()-42000 ,'/');} // Finally, the session is completely destroyed. session_destroy ();?>

The procedure for deleting a Session is as follows:

  1. Session_start ()
  2. $ _ SESSION = array ()/unset ($ _ SESSION ['XXX'])
  3. Session_destroy ()

Solve the problem that PHP Session does not expire and SessionId remains unchanged.

Session collection mechanism:

PHP uses the Garbage Collection process to recycle expired sessions. However, not every session creation can evoke the 'garbage collection 'process. gc is started based on a certain probability. This is mainly due to the consideration of server performance. each session triggers gc. if the page views are large, the server cannot afford it. However, gc is enabled based on a certain probability. when the traffic volume is large, the session expiration mechanism can run normally, and the server efficiency is reduced. The details are derived from years of experience.

Three parameters related to PHP session expiration (in php. ini ):

  1. Session. gc_probability = 1
  2. Session. gc_pisor = 1000
  3. Session. gc_maxlife time = 1440

Gc startup probability = gc_probability/gc_pisor = 0.1%

Session expiration time gc_maxlifetime unit: Seconds

When a web service is officially provided, the session expiration probability needs to be comprehensively considered based on the web service page views and server performance. It is obviously unwise to enable gc for each session. it feels a bit "luck" and a little less likely to hit the page if the traffic is small. During my local testing, I almost never got hit, and the sessionid remains unchanged for several days, even if the machine is restarted. During the test, this expiration probability value must be set to a higher hit probability.

By modifying the expiration probability value of the php configuration file, you can set the session expiration by "Taking Chances". Is there a better way?

The session class written below can completely solve the problem that the session does not expire and the sessionid remains unchanged.

<? Php/*** extended Session class (simple encapsulation) ** @ author slimboy **/class Session {/*** initialization */static function _ init () {ini_set ('session. auto_start ', 0); // Session: start ();}/*** start Session */static function start () {session_start ();} /*** set Session ** @ param $ name Session name * @ param $ value * @ param $ time timeout (seconds) */public static function set ($ name, $ value, $ time) {if (empty ($ time) {$ time = 1800; // Default value} $ _ SESSION [$ name] = $ value; $ _ SESSION [$ name. '_ expires'] = time () + $ time;}/*** get Session value ** @ param $ name Session name */public static function get ($ name) {// check whether the Session has expired if (isset ($ _ SESSION [$ name. '_ expires']) & $ _ SESSION [$ name. '_ E xpires']> time () {return $ _ SESSION [$ name];} else {Session: clear ($ name); return null ;}} /*** set the Session Domain ** @ param $ sessionDomain * @ return string */stati C function setDomain ($ sessionDomain = null) {$ return = ini_get ('session. cookie_domain '); if (! Empty ($ sessionDomain) {ini_set ('session. cookie_domain ', $ sessionDomain); // Cross-domain access Session} return $ return ;} /*** clear a Session value ** @ param $ name Session name */static function clear ($ name) {unset ($ _ SESSION [$ name]); unset ($ _ SESSION [$ name. '_ expires']);}/*** reset and destroy Session */static function destroy () {unset ($ _ SESSION); session_destroy ();} /*** get or set the Session id */static function sessionid ($ id = null) {r Eturn session_id ($ id) ;}}?> Simple call: <? Php // set session Session: set ('userid', $ UserId, 3600); // Read session $ userid = Session: get ('userid');?>

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.