Home > Backend Development > PHP Tutorial > An in-depth explanation of PHP Session and how to keep it from expiring_php skills

An in-depth explanation of PHP Session and how to keep it from expiring_php skills

WBOY
Release: 2016-05-16 20:08:21
Original
1041 people have browsed it

COOKIE technology is used in the implementation of SESSION. SESSION will save a COOKIE containing session_id (SESSION number) on the client side; other session variables, such as session_name, etc., will be saved on the server side. When the user requests the server, the session_id is also sent to the server. By extracting the variables saved on the server side through the session_id, you can identify who the user is. At the same time, it is not difficult to understand why SESSION sometimes fails.

When the client disables COOKIE (click "Tools" - "Internet Options" in IE, click "Security" - "Custom Level" item in the pop-up dialog box, and set "Allow each conversation COOKIE" (disabled), session_id will not be passed, and SESSION will become invalid. However, php5 can automatically check the cookie status on the Linux/Unix platform. If the client is disabled, the system will automatically append the session_id to the URL and pass it. Windows hosts do not have this function.

Common functions and usage of Session?
Session_start(): Start a session or return an existing session.
Note: This function has no parameters and the return value is true. If you use cookie-based sessions, the browser must not produce 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 enable session.auto_start=1 in php.ini, so that you don't need to call session_start() every time before using the session. But there are some limitations to enabling this option, if session.auto_start is indeed enabled, you cannot put objects into the session because the class definition must be loaded before starting the session to recreate the object in the session.
All registered variables will be serialized after the request is completed. Variables that are registered but not defined are marked as undefined. These variables are also not defined by the session module on subsequent accesses unless the user later defines them.

Warning: Some types of data cannot be serialized and therefore cannot be saved in the session. Including resource variables or objects with circular references (that is, one object passes a reference to itself to another object).

Register SESSION variable:
PHP5 uses $_SESSION['xxx']=xxx to register the SESSION global variable. The usage methods of GET, POST and COOKIE are similar.
Note: session_register(), session_unregister, session_is_registered are no longer used under php5, unless register_globle is set to on in php.ini. However, for security reasons, it is strongly recommended to turn off register_globle. The use of HTTP_SESSION_VARS is no longer recommended, and the official recommendation is to use $_SESSION instead. For example:

Page1.php

  <&#63;php
  Session_start(); //使用SESSION前必须调用该函数。

  $_SESSION[‘name']=”我是黑旋风李逵!”; //注册一个SESSION变量

  $_SESSION[‘passwd']=”mynameislikui”;
  $_SESSION[‘time']=time();
  echo '
  通过COOKIE传递SESSION'; //如果客户端支持cookie,可通过该链接传递session到下一页。

  echo '
  . SID . '">通过URL传递SESSION';//客户端不支持cookie时,使用该办法传递session.

  &#63;>

Copy after login

Page2.php

  <&#63;php
  session_start();
  echo $_SESSION['name']; //

  echo $_SESSION['passwd']; //

  echo date('Y m d H:i:s', $_SESSION['time']);
  echo '
  返回山一页';
  &#63;>

Copy after login

There are two ways to pass a session ID:

  1. cookie
  2. URL Parameters

The session module supports both methods. Cookies are more optimized, but since they are not always available, alternatives are also provided. The second method embeds the session ID directly into the middle of the URL.

PHP can convert connections transparently. Unless you are using PHP 4.2 or newer, you need to manually activate it when compiling PHP. Under Unix, use the --enable-trans-sid configuration option. If this configuration option and the runtime option session.use_trans_sid are both activated (php.ini modified), the relative URI will automatically be modified to include the session ID.

session_id
session_id() is used to set or get the current session_id. In php5, you can either use session_id() or obtain the session_id and session_name of the current session through the SID attached to the url.
If session_id() has a specific value, it will replace the current session_id value. The session must be started before using this function: session_start();
When we use session cookies, if a session_id() value is specified, a cookie value will be sent to the client every time session_start() is started. Regardless of whether the current session_id is equal to the specified value.
If session_id() does not specify a value, it returns the current session_id(); if the current session is not started, it returns an empty string.

Check if session exists?
In previous PHP versions, session_is_register() was usually used to check whether the session exists. If you use $_SESSION['XXX']=XXX to register session variables, the session_is_register() function no longer works. You can use
isset($_SESSION[‘xxx’]) instead.

Change session_id session_regenerate_id() returns true if the change is successful and false if it fails.
Using this function can change the session_id for the current session, but does not change other information of the current session. For example:

  <&#63;php
  session_start();
  $old_sessionid = session_id();
  session_regenerate_id();
  $new_sessionid = session_id();
  echo "原始 SessionID: $old_sessionid
  ";
  echo "新的 SessionID: $new_sessionid
  ";
  echo"

  ";

  print_r($_SESSION);
  echo"";
  &#63;>

Copy after login

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, this function must be called before session_start(). Note: session_name cannot only consist of numbers, it must contain at least one letter. Otherwise, a new session id will be generated every time.
Example of session renaming:

$previous_name = session_name("WebsiteID");
echo "新的session名为: $previous_name
";
&#63;>
Copy after login

如何删除session?
1、unset ($_SESSION['xxx']) 删除单个session,unset($_SESSION['xxx']) 用来unregister一个已注册的session变量。其作用和session_unregister()相同。 session_unregister()在PHP5中不再使用,可将之打入冷宫。
unset($_SESSION) 此函数千万不可使用,它会将全局变量$_SESSION销毁,而且还没有可行的办法将其恢复。用户也不再可以注册$_SESSION变量。
2、$_SESSION=array() 删除多个session
3、 session_destroy()结束当前的会话,并清空会话中的所有资源。。该函数不会unset(释放)和当前session相关的全局变量 (globalvariables),也不会删除客户端的session cookie.PHP默认的session是基于cookie的,如果要删除cookie的话,必须借助setcookie()函数。
返回值:布尔值。
功能说明:这个函数结束当前的session,此函数没有参数,且返回值均为true

session_unset() 如果使用了$_SESSION,则该函数不再起作用。由于PHP5必定要使用$_SESSION,所以此函数可以打入冷宫了。

下面是PHP官方关于删除session的案例:

  <&#63;php
  // 初始化session.

  session_start();
  /*** 删除所有的session变量..也可用unset($_SESSION[xxx])逐个删除。****/
  $_SESSION = array();
  /***删除sessin id.由于session默认是基于cookie的,所以使用setcookie删除包含session id的cookie.***/
  if (isset($_COOKIE[session_name()])) {
  setcookie(session_name(), '', time()-42000, '/');
  }

// 最后彻底销毁session.

  session_destroy();
  &#63;>

Copy after login

由此我们可以得出删除Session的步骤:

  1. session_start()
  2. $_SESSION=array()/unset($_SESSION['xxx'])
  3. session_destroy()

解决PHP Session不过期以及SessionId保持不变的问题

session 回收机制:

PHP采用Garbage Collection process对过期session进行回收,然而并不是每次session建立时,都能够唤起 ‘garbage collection' process ,gc是按照一定概率启动的。这主要是出于对服务器性能方面的考虑,每个session都触发gc,浏览量大的话,服务器吃不消,然而按照一定概率开启gc,当流览量大的时候,session过期机制能够正常运行,而且服务器效率得到节省。细节应该都是多年的经验积累得出的。

三个与PHP session过期相关的参数(php.ini中):

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

gc启动概率 = gc_probability / gc_divisor = 0.1%

session过期时间 gc_maxlifetime 单位:秒

当web服务正式提供时,session过期概率就需要根据web服务的浏览量和服务器的性能来综合考虑session过期概率。为每个session都开启gc,显然是不明智的,感觉有点“碰运气”的感觉,要是访问量小命中几率就小。我在本机测试过程中,几乎都没有被命中过,sessionid几天都不变,哪怕机器重启。测试过程中,这个过期概率值要设置大一点命中几率才高点。

通过修改php配置文件的过期概率值,可以“碰运气”式的设置session过期,那有没有更好的办法呢?

下面写的这个session类可以彻底解决session不过期以及sessionid不变的问题。

<&#63;php
 /**
 * 扩展Session类(简单封装)
 * 
 * @author slimboy
 *
 */
class Session { 
 
   /**
   * 初始化
   */
  static function _init(){ 
    ini_set('session.auto_start', 0); 
    //Session::start(); 
   } 
   
   /**
   * 启动Session
   */
  static function start() { 
    session_start(); 
  } 
 
   /**
   * 设置Session
   * 
   * @param $name Session名称
   * @param $value 值
   * @param $time 超时时间(秒)
   */
  public static function set($name,$value,$time){ 
    if(empty($time)){ 
      $time = 1800; //默认值 
     } 
    $_SESSION[$name] = $value; 
    $_SESSION[$name.'_Expires'] = time() + $time; 
  } 
   
   /**
   * 获取Session值
   * 
   * @param $name Session名称
   */
  public static function get($name){ 
    //检查Session是否已过期 
     if(isset($_SESSION[$name.'_Expires']) && $_SESSION[$name.'_E
 xpires']>time()){ 
      return $_SESSION[$name]; 
    }else{ 
      Session::clear($name); 
      return null; 
    } 
  } 
   
    
   /**
   * 设置Session Domain
   * 
   * @param $sessionDomain 域
   * @return string
   */
  static function setDomain($sessionDomain = null) { 
    $return = ini_get('session.cookie_domain'); 
    if(!empty($sessionDomain)) { 
      ini_set('session.cookie_domain', $sessionDomain);//跨
 域访问Session 
     } 
    return $return; 
  } 
   
    
   /**
   * 清除某一Session值
   * 
   * @param $name Session名称
   */
  static function clear($name){ 
    unset($_SESSION[$name]); 
    unset($_SESSION[$name.'_Expires']); 
  } 
   
    
   /**
   * 重置销毁Session
   */
  static function destroy(){ 
    unset($_SESSION); 
    session_destroy(); 
  } 
   
    
   /**
   * 获取或设置Session id
   */
  static function sessionid($id=null){ 
    return session_id($id); 
  } 
 
}
&#63;>
简单调用:
 
<&#63;php
  //设置session 
  Session::set('UserId', $userid, 3600); 
  //读取session
  $userId = Session::get('UserId');
&#63;>
Copy after login

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template