How PHP keeps the session out of date

Source: Internet
Author: User
This article mainly introduces the method of explaining PHP session in depth and how to keep it out of date, including the explanation of the session recovery mechanism and the solution of the problem that SessionID remains unchanged. We hope to help you.

In the implementation of the session using cookie technology, session will save a session_id (session number) in the client cookie, the server side to save other session variables, such as Session_name and so on. When the user requests the server also sends the session_id to the server, through session_id extracts the variable which is saved on the server side, can identify the user is who. It is also not difficult to understand why the session sometimes fails.

When the client disables the cookie (click "Tools"-"Internet Options" in IE, click "Security"-"Custom Level" in the Pop-up dialog box, "Allow each conversation cookie" to be disabled), the session_id will not be delivered, and the session expires. However PHP5 on the Linux/unix platform can automatically check the cookie status, if the client is set to disable, the system automatically attaches the session_id to the URL to pass. The Windows host does not have this feature.

Session common functions and usage?
Session_Start (): Starts a session or returns a session that already exists.
Description: This function has no parameters and the return value is true. If you use a cookie-based session (Cookie-based sessions), the browser cannot have any output before using session_start (), otherwise the following error will occur:
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 that you don't need to call session_start () before you use the session. However, there are some restrictions on enabling this option, and if you do enable Session.auto_start, you cannot put an object into a session because the class definition must be loaded before starting the session to rebuild the object in the session.
All registered variables will be serialized after the request is finished. A variable that has been registered but not defined is marked as undefined. In subsequent accesses, these variables are not defined by the session module unless they are defined later by the user.

Warning: Some types of data cannot be serialized and therefore cannot be saved in the session. Includes a resource variable or an object that has a circular reference (that is, an object passes a reference to itself to another object).

Register Session Variables:
PHP5 uses $_session[' xxx ']=xxx to register the SESSION global variable. It is similar to the Get,post,cookie method.
Note: Session_register (), Session_unregister, session_is_registered is no longer used under PHP5, unless PHP.ini is set to on in Register_globle, However, for security reasons, it is highly recommended to close register_globle. Http_session_vars also do not advocate the use of, the official proposed to replace it with $_session. For example:

page1.php

  <?php  session_start ();//You must call this function before using the Session.  $_session[' name ']= "I am a black tornado Li Kui!"; Register a SESSION variable  $_session[' passwd ']= "Mynameislikui";  $_session[' time ']=time ();  Echo '  passes the session through a cookie ';//If the client supports cookies, the session can be passed to the next page via the link.  Echo '  . Sid. ' > Pass the session via URL ';//When the client does not support cookies, use this method to pass the 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 the Mountain page ';  ? >

There are two ways of passing a session ID:

    1. Cookies

    2. URL parameters

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

PHP can transparently convert connections. Unless you are using PHP 4.2 or later, you need to manually activate PHP when compiling. Under Unix, configure the options with--enable-trans-sid. If both this configuration option and the Run-time option Session.use_trans_sid are activated (modify php.ini), the relative URI is automatically modified to contain the session ID.

session_id
SESSION_ID () is used to set or get the current session_id. The php5 can either use session_id (), or the session_id and Session_name of the current session can be obtained by appending the SID on the URL.
If session_id () has a specified value, the current session_id value will be replaced. The session must be started before using the function: session_start ();
When we use session cookies, if a session_id () value is specified, each boot session_start () will send a cookie value to the client. Regardless of whether the current session_id is equal to the specified value.
SESSION_ID () returns the current session_id () If no value is specified, or an empty string if the current session is not started.

Check to see if the session exists?
In previous versions of PHP, Session_is_register () was commonly used to check if a session exists, and if you use $_session[' XXX ']=xxx to register a conversation variable, session_is_register () function no longer works. You can use
Isset ($_session[' xxx ') to replace.

Change session_id session_regenerate_id () The change succeeds returns True, and false returns if it fails.
Use this function to change the session_id for the current session without changing the other information for 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. If you want to change the name of the current session, you must call the function before Session_Start (). Note: Session_name cannot consist of numbers only, it contains at least one letter. Otherwise, a new session ID will be generated at every moment of the day.
Example of Session renaming:

$previous _name = Session_name ("WebSiteID"); Echo "New session Name: $previous _name";? >

How do I delete a session?
1, unset ($_session[' xxx ']) delete a single session,unset ($_session[' xxx ') to unregister a registered SESSION variable. Its effect is the same as Session_unregister (). Session_unregister () is no longer used in PHP5 and can be limbo.
Unset ($_session) This function must not be used, it will destroy the global variable $_session, and there is no viable way to restore it. Users can no longer register $_session variables.
2, $_session=array () delete more than one SESSION
3. Session_destroy () ends the current session and empties all resources in the session. The function does not unset (releases) the global variables associated with the current session (GlobalVariables), nor does it delete the client's session cookie. PHP's default session is cookie-based, and if you want to delete a cookie, you must use the Setcookie () function.
Return value: A Boolean value.
Function Description: This function ends the current session, this function has no parameters and the return value is True

Session_unset () If $_session is used, the function no longer works. Since PHP5 is bound to use $_session, this function can be limbo.

The following is the official PHP case to delete the session:

  <?php  //Initialize session.  Session_Start ();  /*** Delete all the session variables: Unset ($_session[xxx]) can also be deleted individually. /  $_session = Array ();  /*** Delete the Sessin ID. Because the session is COOKIE-based by default, use Setcookie to delete the cookie.***/  if (isset ($_cookie[session_name) that contains the session ID. ()]) {  Setcookie (Session_name (), ", Time () -42000, '/');  } Finally, the session is completely destroyed.  Session_destroy ();  ? >

Thus we can draw the steps to delete the session:

    1. Session_Start ()

    2. $_session=array ()/unset ($_session[' xxx ')

    3. Session_destroy ()

Solve the problem that the PHP session does not change and SessionID remains unchanged

Session recovery mechanism:

PHP uses garbage Collection process to recover expired sessions, but not every time the session is established, the ' garbage Collection ' process can be aroused, and the GC is started in a certain probability. This is mainly out of the server performance considerations, each session triggered GC, browsing volume, the server is too much, but in accordance with a certain probability to open the GC, when the flow of large, the session expiration mechanism can run normally, and the efficiency of the server is saved. The details should be accumulated over years of experience.
Three parameters related to the expiration of the PHP session (php.ini):

    1. session.gc_probability = 1

    2. Session.gc_pisor = 1000

    3. Session.gc_maxlifetime = 1440

GC start probability = Gc_probability/gc_pisor = 0.1%
Session Expiration Time Gc_maxlifetime units: seconds
When the Web service is formally provided, the session expiration probability needs to consider the session expiration probability according to the Web service's browsing volume and the server's performance. It is obviously unwise to turn on the GC for each session, and feel a bit of a "chance" if the number of hits is small. I was in the test process, almost no hit, SessionID days are unchanged, even if the machine restarts. During the test, this expiration probability value is set to a greater chance of hit.
By modifying the PHP configuration file expiration probability value, you can "luck" set the session expires, there is no better way to do it?

The following session class can completely solve the problem of the session and SessionID unchanged.

<?php/** * Extended Session Class (Simple package) * * @author Slimboy * */class Session {/** * initialize */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 value * @param $time Time Out (seconds) */public static F     Unction set ($name, $value, $time) {if (empty ($time)) {$time = 1800;//default} $_session[$name] = $value; $_session[$name. '   _expires '] = time () + $time;      }/** * gets session value * * @param $name Session name */public static function get ($name) {//Check if session has expired if (Isset ($_session[$name. ' _expires ']) && $_session[$name. '     _e xpires ']>time ()) {return $_session[$name];       }else{session::clear ($name);     return null; }}/** * Set session domain * * @param $sessionDomain field * @return String */static function Setdoma In ($sessiOndomain = null) {$return = Ini_get (' Session.cookie_domain '); if (!empty ($sessionDomain)) {ini_set (' Session.cookie_domain ', $sessionDomain);//cross-domain Access session} return $retu   Rn /** * Clears a session value * * @param $name Session name */static function Clear ($name) {unset ($_session[$     Name]); Unset ($_session[$name. '   _expires ']);     }/** * Reset Destroy SESSION */static function Destroy () {unset ($_session);   Session_destroy ();   }/** * Gets or sets the session ID */static function SessionID ($id =null) {return session_id ($id);   }}?> Simple call: <?php//Set Session session::set (' UserId ', $userid, 3600); Read Session $userId = session::get (' userId ');? >

Related recommendations:

Introduction to the PHP session

PHP Advanced Tutorial: PHP Cookies

PHP Cookies Operation class (with source code)

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.