A thorough explanation of PHP session and how to maintain its _php skills

Source: Internet
Author: User
Tags class definition echo date garbage collection session id php session sessions setcookie

In the implementation of the session, cookie technology is used to save a cookie containing the session_id on the client, and to save additional session variables on the server side, such as Session_name and so on. When the user requests the server also sends the SESSION_ID together to the server, through session_id extracts is saved on the server side the variable, can identify the user is who. It is also not difficult to understand why the session sometimes fails.

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

Session common function and usage?
session_start (): Starts a session or returns a session that already exists.
Note: 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 (), or 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 the session.auto_start=1 in php.ini so you don't need to invoke session_start () every time you use the session. However, there are some limitations on enabling this option, and if Session.auto_start is enabled, you cannot put the object into a session because the class definition must be loaded before the session is started to rebuild the object in the session.
All registered variables are serialized after the end of the request. A variable that is registered but undefined is marked as undefined. These variables are also not defined by the session module in subsequent accesses, unless they are defined later by the user.

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

Register Session Variable:
PHP5 registers the session global variable with the $_session[' xxx ']=xxx. It is similar to the way Get,post,cookie is used.
Note: Session_register (), Session_unregister, session_is_registered are no longer used under PHP5 unless the php.ini is set to on in Register_globle, However, for security reasons, it is strongly recommended that register_globle be closed. Http_session_vars also does not advocate the use, the official proposal uses $_session to replace it. For example:

page1.php

  <?php
  session_start ()////The function must be called before using session.

  $_session[' name ']= "I am the black whirlwind likui!"; Register a Session variable

  $_session[' passwd ']= ' Mynameislikui ';
  $_session[' time ']=time ();
  Echo passes session
  via cookie;//If the client supports cookies, you can pass the session to the next page through the link.

  Echo '
  . Sid. ' > Pass session via URL;//client does not support cookies, 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 '
  return to Mountain page ';
  ? >

There are two methods of passing a session ID:

    1. Cookies
    2. URL parameters

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

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

session_id
session_id () is used to set or obtain the current session_id. either session_id () can be used in php5, or the session_id and Session_name of the current session can be obtained by the SID attached to the URL.
If session_id () has a specified value, the current session_id value is replaced. You must start a session before using this function: session_start ();
When we use session cookies, if a session_id () value is specified, each boot session_start () sends a cookie value to the client. Regardless of whether the current session_id is equal to the specified value.
SESSION_ID () returns an empty string if no value is specified, the current session_id () is returned, and the current session does not start.

Check if session exists?
In previous versions of PHP, Session_is_register () was often used to check for the existence of sessions, and if you used $_session[' XXX ']=xxx to register session variables, 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 session_id for the current session, but not to change 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 only numbers, it contains at least one letter. Otherwise, a new session ID will be generated at every moment.
Example of Session name change:

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

How do I delete a session?
1. unset ($_session[' xxx ') deletes a single session,unset ($_session[' xxx ')) to unregister a registered session variable. The effect is the same as Session_unregister (). Session_unregister () is no longer used in PHP5, and can be put into the doghouse.
Unset ($_session) This function must not be used, it will destroy the global variable $_session, and there is no feasible way to restore it. Users can no longer register $_session variables.
2, $_session=array () Delete multiple sessions
3. Session_destroy () ends the current session and empties all resources in the session ... The function does not unset (release) the global variable (globalvariables) associated with the current session, nor does it delete the client's session cookie. PHP default session is based on cookies, and if you want to delete cookies, you must use the Setcookie () function.
Return value: Boolean value.
Function Description: This function ends the current session, this function has no arguments, and the return value is True

Session_unset () The function no longer works if $_session is used. Since PHP5 is bound to use $_session, this function can be shelved.

Here is the official PHP case for deleting the session:

  <?php
  //initialization session.

  Session_Start ();
  /*** Delete all Session variables ... Unset ($_session[xxx]) can also be deleted individually. /
  $_session = Array ();
  /*** deletes the Sessin ID. Because the session defaults to cookies, use Setcookie to delete the cookie.***/if (Isset) containing the session ID
  ($_cookie[session_name ()]) {
  Setcookie (session_name (), ', Time () -42000, '/');
  }

Finally completely destroy session.

  Session_destroy ();
  ? >

From this we can draw the step of deleting the session:

    1. Session_Start ()
    2. $_session=array ()/unset ($_session[' xxx ')
    3. Session_destroy ()

Solve the problem of PHP session and SessionID remain unchanged

Session recovery mechanism:

PHP uses garbage Collection process to recycle expired session, however not every session is established, can arouse ' garbage Collection ' process, GC is started according to a certain probability. This is mainly due to the server performance considerations, each session triggers GC, browsing volume, the server is too much, however, according to a certain probability to open the GC, when the flow of large, session expiration mechanism can run normally, and the server efficiency is saved. The details should be accumulated over years of experience.

Three parameters associated with the PHP session expiration (php.ini):

    1. session.gc_probability = 1
    2. Session.gc_divisor = 1000
    3. Session.gc_maxlifetime = 1440

GC startup probability = Gc_probability/gc_divisor = 0.1%

Session Expiration Gc_maxlifetime Unit: SEC

When the Web service is formally provided, the session expiration probability needs to consider the session expiration probability according to the browsing volume of the Web service and the performance of the server. For each session to open the GC, it is obviously unwise, feel a bit of "luck" feeling, if the number of visits small hit chance. In the course of my native testing, I was almost never hit, SessionID for a few days, even if the machine reboots. During the test, the expiration probability value should be set to a larger hit chance.

By modifying the PHP configuration file expiration probability value, you can "luck" type of setting session expiration, there is no better way?

This session class is written below to solve the problem of SessionID and no change.

<?php/** * Extended Session Class (Simple encapsulation) * * * * @author slimboy * * * * */class Session {/** * initialization/static functio 
    n _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 timeout (sec)/public static function set ($name, $value, $time) {if (empty ($time)) {$time = 1800;//Default value} $_session[$name] 
    = $value; $_session[$name. ' 
  _expires '] = time () + $time; /** * Gets the session value * * @param $name Session name */public static function get ($name) {//Check Sessio N 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 Domain * @return string/static function setdomain ($sessionDomain = null) {$return = Ini_get (' Session.cookie_d 
    Omain '); if (!empty ($sessionDomain)) {ini_set (' Session.cookie_domain ', $sessionDomain);//cross-domain Access session} return $ 
  Return /** * Clears a session value * @param $name session name/static function clear ($name) {unset ($_ 
    session[$name]); Unset ($_session[$name. ' 
  _expires ']); 
    /** * Reset 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 ');?>

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.