Home >Backend Development >PHP Problem >Detailed explanation of session usage in php
Declaration and use of Session
The setting of Session is different from Cookie and must be done first. To start, session_start() must be called in PHP. The syntax format of the session_start() function is as follows:
Bool session_start(void) //Create a Session, start a session, and initialize the Session
Note: There cannot be any output before the session_start() function
When you visit the website for the first time, the Seesion_start() function will create a unique Session ID and automatically save the Session ID to the client cookie through the HTTP response header. At the same time, a file named after the Session ID is also created on the server side to save the user's session information. When the same user visits this website again, the Seesion ID saved in the cookie will be automatically brought over through the HTTP request header. At this time, the Session_start() function will not allocate a new Session ID, but will Search the server's hard disk for a Session file with the same name as the Session ID, read out the session information previously saved for this user, and apply it in the current script to achieve the purpose of tracking this user. Session is used in the form of an array, such as: $_SESSION['session name']
Related topic recommendations:php session (including pictures, texts and videos , case)
Register a session variable and read Session
When using Session variables in PHP, in addition to starting it, you also need to go through the registration process. Registration and reading of Session variables are completed by accessing the $_SESSION array. Key names in the $_SESSION associative array have the same naming rules as ordinary variables in PHP. The code to register Session variables is as follows:
2d06ed5fb15b10d20ed0b96cd5596fb8
After executing the script, the two Session variables will be saved in a file on the server side. The location of the file is through the php.ini file. In the session In the directory specified by the .save_path attribute.
Unregister variables and destroy Session
When a Session variable is used, it can be deleted. When a session is completed, it can also be destroyed. If the user logs out of the Web system, he needs to be provided with a logout function and all his information will be destroyed in the server. To destroy all data related to the current Session, you can call the session_destroy() function to end the current session and clear all resources in the session. The syntax format of this function is as follows:
bool session_destroy(void) //销毁和当前Session有关的所有资料
This function will not release the variables related to the current Session, nor will it delete the SessionID saved in the client cookie. Because the $_SESSION array and the custom array are used the same, we can use the unset() function to release a single variable registered in the Session. As shown below:
unset($_SESSION['键名']);
Be careful not to use unset($_SESSION) to delete the entire $_SESSION array, so you will no longer be able to register variables through the $_SESSION super global array. But if you want to delete all variables registered by a user in the Session, you can directly assign the array variable $_SESSION to an empty array. As shown below:
$_SESSION=array()
PHP's default Session is based on Cookie. The SessionID is stored in the client's Cookie by the server. Therefore, when logging out of the Session, you also need to clear the SessionID saved in the Cookie, and this requires the help of setCookie. () function is completed. In a PHP script, the Session name can be obtained by calling the session_name() function. Delete the SessionID saved in the client cookie. The code is as follows:
40000d5da5a09bf9f762f8f3fc8cf2cf>
It can be concluded from the previous introduction that the session logout process requires a total of 4 steps. In the following example, the complete four-step code is provided. Running the script will close the Session and destroy all resources related to this session. The code is as follows:
6ee5c7f84218ae64e4d5f014c2d118e4
session’s phpini configuration options
Several common configuration options related to the php.ini file and Session:
## session.auto_start = 0 ; Initialized when the request starts
session
session.cache_expire = 180 ; Set the session document in the cache in n minutes Expired later
session.cookie_lifetime = 0; Set the storage time of
cookie in seconds, which is equivalent to setting the expiration time of
Session, When it is 0, it means that it will not be used until the browser is restarted
session.auto_start=1, so that there is no need to call
session_start() every time before using
sessionNot recommended .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.
session.cookie_path = / ; cookie的有效路径session.cookie_domain = ; cookie的有效域session.name = PHPSESSID; 用在cookie里的session的名字session.save_handler = files ; 用于保存/取回数据的控制方式session.save_path = /tmp ; 在 save_handler 设为文件时传给控制器的参数, 这是数据文件将保存的路径.session.use_cookies = 1 ; 是否使用cookies
Session’s automatic garbage collection mechanism
可以通过session_destroy()
函数在页面中提供一个“退出”按钮,通过单击销毁本次会话。但如果用户没有单击退出按钮,而是直接关闭浏览器,或断网等情况,在服务器端保存的Session文件是不会删除的。虽然关闭浏览器,下次需要重新分配一个新的Session ID重新登录,但这只是因为在php.ini中的设置seesion.cookie_lifetime=0,来设定Session ID在客户端Cookie中的有效限期,以秒为单位指定了发送到浏览器的Cookie的生命周期。当系统赋予Session有效期限后不管浏览器是否开启,Session ID都会自动消失。而客户端Session ID消失服务器端保存的Session文件并没有被删除。所以没有被Sessoin ID引用的服务器端Session文件,就成为了“垃圾”。
服务器保存的Session文件就是一个普通文本文件,所以都会有文件修改时间。“垃圾回收程序”启动后就是根据Session文件的修改时间,将所有过期的Session文件全部删除。通过在php.ini中设置session.gc_maxlifetime选项来指定一个时间(单位:秒),例如设置该选项值为1440(24分钟)。“垃圾回收程序”就会在所有Session文件中排查,如果有修改时间距离当前系统时间大于1440秒的就将其删除。
“session垃圾回收程序”是怎样的启动机制呢?“垃圾回收程序”是在调用session_start()函数时启动的。而一个网站有多个脚本,没有脚本又都要使用session_start()函数开启会话,又会有很多个用户同时访问,这就很可能session_start()函数在1秒内被调用N次,而如果每次都会启动“session垃圾回收程序”,这样是很不合理的。可以通过php.ini文件中修改“session.gc_probability和session.gc_pisor”两个选项,设置启动垃圾回收程序的概率。会根据“session.gc_probability/session.gc_pisor”公示计算概率,例如选项session.gc_probability=1,而选项session.gc_pisor=100,这样的概率就是“1/100”,即session_start()函数被调用100次才会有一次可能启动“垃圾回收程序”。
php.ini中相关的配置
session.cookie_lifetime=0;
关闭浏览器相应的cookie文件即被删除
session.gc_maxlifetime;
设置过期session时间,默认1440秒(24分钟)
session.gc_probability/session.gc_pisor;
启动垃圾回收机制的概率(建议值为1/1000——5000)
cookie禁用时通过URL传递session的ID
使用Session跟踪一个用户,是通过在各个页面之间传递唯一的Session ID,并通过Session ID提取这个用户在服务器中保存的Session变量。常见的Session ID传送方法有以下两种。
第一种方法是基于cookie的方式传递session ID,这种方式更优,但不总是可用, 因为用户在客户端可以屏蔽cokie;
第二种方法是通过url参数进行传递,直接将session ID嵌入到URL中去。
在Session的实现中通常都是采用Cookie的方式,客户端保存的Session ID就是一个Cookie。当客户禁用Cookie时,Session ID就不能在Cookie中保存,也就不能在页面之间传递,此时Session失效。不过PHP5在Linux平台可以自动检查Cookie状态,如果客户端禁用它,则系统自动把Session ID附加到URL上传送。而使用Windows系统作为Web服务器则无此功能。
在PHP中提出了跟踪Session的另一种机制,如果客户浏览器不支持Cookie,则PHP可以重写客户请求的URL,把Session ID添加到URL信息中。可以手动地在每个超链接的URL中都加上一个Session ID,但工作量比较大,不建议使用这种方法。如下所示:
<?php //开启session session_start(); //在每个URL后面附加上参数,变量名为session_name()获取名称,值通过session_id()获取 echo '<a href="demo.php?'.session_name().'='.session_id().'">连接演示</a>'; ?> 在使用Linux系统做服务器时,则在编辑PHP时如果使用了–enable-trans-sid配置选项,和运行时选项session.use_trans_sid都被激活,在客户端禁用Cookie时,相对URL将被自动修改为包含会话ID。如果没有这么配置,或者使用Windows系统作为服务器时,可以使用常量SID。该常量在会话启动时被定义,如果客户端没有发送适当的会话Cookie,则SID的格式为session_name=session_id,否则就为一个空字符串。因此可以无条件地将其嵌入到URL中去。在下例中使用两个脚本程序,演示了Session ID的传送方法。 <?php session_start(); $_SESSION["username"]="admin"; echo "session ID:".session_id()."<br>"; ?>
推荐教程: 《php教程》
The above is the detailed content of Detailed explanation of session usage in php. For more information, please follow other related articles on the PHP Chinese website!