Home>Article>Backend Development> PHP method to keep Session from expiring
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
通过URL传递SESSION';//客户端不支持cookie时,使用该办法传递session. ?>
Page2.php
There are two ways to pass a session ID:
cookie
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:
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的案例:
由此我们可以得出删除Session的步骤:
session_start()
$_SESSION=array()/unset($_SESSION['xxx'])
session_destroy()
解决PHP Session不过期以及SessionId保持不变的问题
session 回收机制:
PHP采用Garbage Collection process对过期session进行回收,然而并不是每次session建立时,都能够唤起 ‘garbage collection' process ,gc是按照一定概率启动的。这主要是出于对服务器性能方面的考虑,每个session都触发gc,浏览量大的话,服务器吃不消,然而按照一定概率开启gc,当流览量大的时候,session过期机制能够正常运行,而且服务器效率得到节省。细节应该都是多年的经验积累得出的。
三个与PHP session过期相关的参数(php.ini中):
session.gc_probability = 1
session.gc_pisor = 1000
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不变的问题。
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); } } ?> 简单调用:
相关推荐:
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!