Home  >  Article  >  Backend Development  >  Detailed explanation of how to use Session in php_PHP tutorial

Detailed explanation of how to use Session in php_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:18:02786browse

Detailed explanation of how to use Session in php

The 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 Session, start a session, and initialize 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

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 the Session variable is as follows:

The code is as follows


//Start session initialization
session_start();
//Register the session variable and assign it to the name of a user
$_SESSION["username"]="skygao";
//Register the session variable and assign it to a user's ID
$_SESSION["uid"]=1;
?>

 代码如下  


//启动session的初始化
session_start();
//注册session变量,赋值为一个用户的名称
$_SESSION["username"]="skygao";
//注册session变量,赋值为一个用户的ID
$_SESSION["uid"]=1;
?>

After executing this 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.

Unregister variables and destroy Session

When a Session variable is used, it can be deleted, and 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 variables related to the current Session, nor will it delete the Session saved in the client cookie

ID. Because the use of the $_SESSION array and the custom array are 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 careful not to use unset($_SESSION) to delete the entire $_SESSION array. This will no longer allow you 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, Session

The ID is stored in the client's Cookie by the server, so 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 saved in the client cookie

ID, the code is as follows:

 代码如下  
//判断Cookie中是否存在session ID
if(isset($_COOKIE[session_name()])){
//删除包含Session ID的cookie,注意第四个参数一定要和php.ini设置的路径相同
setcookie(session_name(),'',time()-3600,'/');
}
?>

From the previous introduction, it can be concluded 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 looks like this:

The code is as follows

//Step one: Open Session and initialize
session_start();

//Part 2: Delete all Session variables. You can also use unset($_SESSION[XXX]) to delete them one by one
$_SESSION = array();

//Part 3: If using a cookie-based session, use setCookkie() to delete the cookie containing the Session ID
if(isset($_COOKIE[session_name()])) {
setCookie(session_name(), "", time()-42000, "/");
}

//Part 4: Completely destroy the session
session_destroy();

?>

 代码如下  

//第一步:开启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, "/");
}

//第四部:最后彻底销毁session
session_destroy();

?>

Session phpini configuration options

Several common configuration options related to the php.ini file and Session:

session.auto_start = 0 ; initialize session when request starts

Session.cache_expire = 180 ; Set session documents in the cache to expire after n minutes

Session.cookie_lifetime = 0; Set the cookie storage time in seconds, which is equivalent to setting the Session expiration time. When it is 0, it means until the browser is restarted

Session.auto_start=1, so that you don’t need to call session_start() every time you use the session. It is not recommended. However, there are some restrictions on enabling this option. If session.auto_start is indeed enabled, you cannot put objects into the session. in because the class definition must be loaded before starting the session to recreate the object in the session.

Session.cookie_path = / ; Valid path of cookie

Session.cookie_domain = ; Valid domain of cookie

Session.name = PHPSESSID; The name of the session used in the cookie

Session.save_handler = files; Control method for saving/retrieving data

Session.save_path = /tmp ; The parameter passed to the controller when save_handler is set to a file. This is the path where the data file will be saved.

Session.use_cookies = 1 ; Whether to use cookies

Session’s automatic garbage collection mechanism

You can provide an "Exit" button on the page through the session_destroy() function to destroy this session by clicking on it. However, if the user does not click the exit button, but directly closes the browser, or disconnects from the Internet, the Session file saved on the server will not be deleted. Although you close the browser and need to reassign a new Session ID to log in again next time, this is only because the setting seesion.cookie_lifetime=0 in php.ini sets the validity period of the Session ID in the client cookie. Specifies the lifetime of the cookie sent to the browser in seconds. When the system gives the Session a validity period, the Session ID will automatically disappear regardless of whether the browser is opened or not. When the client's Session ID disappears, the Session file saved on the server has not been deleted. Therefore, server-side Session files that are not referenced by Sessoin ID become "garbage".

The Session file saved by the server is an ordinary text file, so it will have file modification time. After the "Garbage Collection Program" is started, all expired Session files will be deleted based on the modification time of the Session file. Specify a time (unit: seconds) by setting the session.gc_maxlifetime option in php.ini, for example, set the option value to 1440 (24 minutes). The "Garbage Collection Program" will check all Session files and delete them if the modification time is greater than 1440 seconds from the current system time.

What is the startup mechanism of the "session garbage collection program"? The "garbage collection program" is started when the session_start() function is called. A website has multiple scripts. If there are no scripts, the session_start() function must be used to open the session, and there will be many users accessing it at the same time. It is very likely that the session_start() function will be called N times in 1 second, and if every The "session garbage collection program" will be started every time, which is very unreasonable. You can set the probability of starting the garbage collection program by modifying the "session.gc_probability and session.gc_divisor" options in the php.ini file. The probability will be calculated based on the "session.gc_probability/session.gc_divisor" publicity. For example, if the option session.gc_probability=1 and the option session.gc_divisor=100, the probability is "1/100", that is, the session_start() function is called 100 times. Only once can the "garbage collection process" be started.

Relevant configurations in php.ini

Session.cookie_lifetime=0; The corresponding cookie file will be deleted when the browser is closed

session.gc_maxlifetime; Set the expiration session time, the default is 1440 seconds (24 minutes)

Session.gc_probability/session.gc_divisor; The probability of starting the garbage collection mechanism (recommended value is 1/1000-5000)

Pass the session ID through the URL when cookies are disabled

Using Session to track a user is by passing a unique Session ID between each page, and extracting the Session variable saved by this user in the server through the Session ID. There are two common Session ID transmission methods:

The first method is to pass the session ID based on cookies. This method is better, but it is not always available because users can block cookies on the client;

The second method is to pass it through the url parameter and embed the session ID directly into the URL.

In the implementation of Session, Cookie is usually used, and the Session ID saved by the client is a Cookie. When a customer disables cookies, the Session ID cannot be saved in the cookie and cannot be passed between pages. At this time, the Session becomes invalid. However, PHP5 can automatically check the cookie status on the Linux platform. If the client disables it, the system automatically appends the Session ID to the URL and transmits it. However, using Windows system as a Web server does not have this function.

Another mechanism for tracking Session is proposed in PHP. If the client's browser does not support Cookie, PHP can rewrite the URL requested by the client and add the Session ID to the URL information. You can manually add a Session ID to the URL of each hyperlink, but the workload is relatively large and this method is not recommended. As shown below:

The code is as follows

//Open session
session_start();

//Append parameters after each URL. The variable name is session_name() to obtain the name, and the value is obtained through session_id()
echo 'Connect to demo';
?>
When using a Linux system as a server, if the –enable-trans-sid configuration option is used when editing PHP, and the runtime option session.use_trans_sid is activated, when cookies are disabled on the client, the relative URL will be automatically modified to Contains the session ID. If this is not configured, or when using a Windows system as the server, you can use a constant SID. This constant is defined when the session is started. If the client does not send an appropriate session cookie, the format of the SID is session_name=session_id, otherwise it is an empty string. Therefore it can be embedded into the URL unconditionally. In the following example, two script programs are used to demonstrate the Session ID transmission method.

 代码如下  

//开启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_start();

$_SESSION["username"]="admin";

echo "session ID:".session_id()."
";

?>

Pass Session ID through URL

In the script test2.php, output another user name saved in the Session variable by the test1.php script. The Session ID is output again on this page, and the comparison is used to determine whether the two scripts use the same Session ID. In addition, when turning on or off cookies, pay attention to the changes in the URL in the browser address bar. The code looks like this:
 代码如下  

session_start();

echo $_SESSION["username"]."< br>";
echo "session ID:".session_id()."
";
?>

The code is as follows

session_start();

echo $_SESSION["username"]."< br>";
echo "session ID:".session_id()."
";
?>

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/886551.htmlTechArticleDetailed explanation of how to use Session in php. The declaration and use of Session are different from Cookie. They must be started first. In PHP session_start() must be called. The syntax of the session_start() function...
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