Home  >  Article  >  Backend Development  >  PHP method to keep Session from expiring

PHP method to keep Session from expiring

*文
*文Original
2018-05-18 09:41:454638browse

This article mainly introduces an in-depth explanation of PHP Session and how to keep it from expiring, including an explanation of the Session recycling mechanism and a solution to the problem of the SessionId remaining unchanged. I hope to be helpful.

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 change "Allow each conversation" COOKIE" is set to disabled), session_id will not be passed, and SESSION will be invalid at this time. 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.

php Chinese website learning topic: php session (including pictures, texts, videos, cases)

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 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 you don’t need to start it every time Session_start() must be called before using session. But there are some limitations to enabling this option, if session.auto_start is indeed enabled, you cannot put the object 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

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

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

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

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

  ?>

Page2.php

  <?php
  session_start();
  echo $_SESSION[&#39;name&#39;]; //

  echo $_SESSION[&#39;passwd&#39;]; //

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

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 be automatically 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.
session_id() If no value is specified, the current session_id() is returned; if the current session is not started, an empty string is returned.

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:

  <?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"";
  ?>

session_name() 返回当前session的name或改变当前session的name。如果要改变当前session的name,必须在session_start() 之前调用该函数。注意:session_name不能只由数字组成,它至少包含一个字母。否则会在每时每刻都生成一个新的session id.
session改名示例:

$previous_name = session_name("WebsiteID");
echo "新的session名为: $previous_name
";
?>

如何删除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的案例:

  <?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(), &#39;&#39;, time()-42000, &#39;/&#39;);
  }

// 最后彻底销毁session.

  session_destroy();
  ?>

由此我们可以得出删除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_pisor = 1000

  3. session.gc_maxlifetime = 1440

gc启动概率 = gc_probability / gc_pisor = 0.1%
session过期时间 gc_maxlifetime 单位:秒 
当web服务正式提供时,session过期概率就需要根据web服务的浏览量和服务器的性能来综合考虑session过期概率。为每个session都开启gc,显然是不明智的,感觉有点“碰运气”的感觉,要是访问量小命中几率就小。我在本机测试过程中,几乎都没有被命中过,sessionid几天都不变,哪怕机器重启。测试过程中,这个过期概率值要设置大一点命中几率才高点。
通过修改php配置文件的过期概率值,可以“碰运气”式的设置session过期,那有没有更好的办法呢?

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

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

相关推荐:

php Session的简介

PHP高级教程:PHP Cookies

php Cookies操作类(附源码)

 

The above is the detailed content of PHP method to keep Session from expiring. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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