Home > Article > Backend Development > Detailed explanation on the use of Session in php
You will encounter caching problems in the process of learning PHP. This article will explain the relevant content in detail.
Declaration and use of Session
Session settings are different from Cookie and must be started first. 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']
Register a session variable and read Session
Use Session variables in PHP, in addition to starting, There is also a 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:
The code is as follows
//启动session的初始化 session_start(); //注册session变量,赋值为一个用户的名称 $_SESSION["username"]="skygao"; //注册session变量,赋值为一个用户的ID $_SESSION["uid"]=1; >
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 directory specified by the session.save_path attribute.
Unregistering variables and destroying 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) //Destroy all data related to the current Session
This function will not release the variables related to the current Session, nor will it release the variables related to the current Session. The Session
ID saved in the client cookie will not be deleted. 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['key name']);
Be sure not to use unset($_SESSION) to delete the entire $_SESSION array, otherwise it will no longer pass $_SESSION super global array registered variables. 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, and the Session
ID is stored in the client’s Cookie by the server, so in When logging out of the Session, you also need to clear the SessionID saved in the Cookie, and this must be done with the help of the setCookie() function. In a PHP script, the Session name can be obtained by calling the session_name() function. Delete the Session
ID saved in the client cookie. The code is as follows:
The code is as follows
//Determine whether the session ID
## exists in the cookie. #if(isset($_COOKIE[session_name()])){//Delete the cookie containing the Session ID. Note that the fourth parameter must be the same as the path set in php.inisetcookie(session_name(),'',time()-3600,'/');}>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: The code is as follows//第一步:开启Session并初始化 session_start(); //第二部:删除所有Session的变量,也可以用unset($_SESSION[XXX])逐个删除 $_SESSION = array(); //第三部:如果使用基于Cookie的session,使用setCookkie()删除包含Session ID的cookie if(isset($_COOKIE[session_name()])) { setCookie(session_name(), "", time()-42000, "/"); }//Part 4: Finally completely destroy the session
session_destroy(); > session的phpini配置选项 php.ini文件和Session有关的几个常用配置选项: session.auto_start = 0 ; 在请求启动时初始化session session.cache_expire = 180 ; 设置缓存中的会话文档在 n 分钟后过时 session.cookie_lifetime = 0 ; 设置按秒记的cookie的保存时间,相当于设置Session的过期时间,为0时表示直到浏览器被重启session.auto_start=1, so there is no need to use the session every time Calling session_start() before is not recommended. However, there are some limitations to enabling this option. If session.auto_start is indeed enabled, objects cannot be put into the session because the class definition must be loaded before starting the session to be rebuilt in the session. object.
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 ; 是否使用cookiesSession’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,但工作量比较大,不建议使用这种方法。如下所示:
代码如下
//开启session
session_start();
//在每个URL后面附加上参数,变量名为session_name()获取名称,值通过session_id()获取
echo '连接演示';
>
在使用Linux系统做服务器时,则在编辑PHP时如果使用了–enable-trans-sid配置选项,和运行时选项session.use_trans_sid都被激活,在客户端禁用Cookie时,相对URL将被自动修改为包含会话ID。如果没有这么配置,或者使用Windows系统作为服务器时,可以使用常量SID。该常量在会话启动时被定义,如果客户端没有发送适当的会话Cookie,则SID的格式为session_name=session_id,否则就为一个空字符串。因此可以无条件地将其嵌入到URL中去。在下例中使用两个脚本程序,演示了Session ID的传送方法。
session_start(); $_SESSION["username"]="admin"; echo "session ID:".session_id()." ";
本篇详解了session的相关问题,更多相关知识请关注php中文网。
相关推荐:
The above is the detailed content of Detailed explanation on the use of Session in php. For more information, please follow other related articles on the PHP Chinese website!