This article introduces PHP session control, mainly elaborating on the following points:
• Background/concept of session control
• Cookie maintenance and life cycle (validity time)
• Session maintenance and life cycle (recycling mechanism)
• The difference and connection between cookie and session
• Question 1: Why does the session become invalid after disabling cookies?
• Problem 2: The session is lost in IE browser, and a new session ID will be generated every time the page is refreshed (Firefox browser is normal)
• Simple examples of session and cookie
Understand the concept of session control
To understand a concept, you need to understand its background and the reasons for its creation. Here we introduce the WEB environment and its HTTP protocol. Background generated by session control:
Students who have read information about the HTTP protocol will know that the HTTP protocol is a protocol for mutual communication between the WEB server and the client (browser). It is a stateless protocol. The so-called stateless means that it does not maintain http request data. http Requests are independent and not persistent. In other words, the HTTP protocol does not have a built-in mechanism to maintain the status or relationship between two transactions. When a user requests one page and then requests another page, HTTP will not be able to tell us whether the two requests came from the same user.
We will find it very strange from this. When we usually browse posts in forums or shop on e-commerce websites, as long as we are in this site, no matter how we jump from one page to another, the website will always be the same. Will remember who I am, such as telling you what I bought. How this is done, I guess everyone has guessed it, this is the use of HTTP session control. Track a variable in the website. By tracking the variable, you can establish connections between multiple requests and display different content and pages based on authorization and user identity.
PHP Session Control:
PHP's session session is driven by a unique session ID. The session ID is an encrypted random number, generated by PHP, and will be saved on the client during the life cycle of the session. We know that the client (that is, the browser) only saves data in cookies, so PHP's session ID is generally stored in the cookie of the user's machine. After understanding cookies, we know that the browser can disable cookies, so that the session will become invalid. So there is another mode for PHP session control, which is to pass the session ID in the URL. If we pay a little attention when browsing the website, some URLs have a string that looks like random numbers, then it is very likely that it is session control in the form of URL.
Speaking of this, some people may have questions. The client only saves a session ID. So where are the session variables saved in the session control, such as the list of items you bought when shopping, etc., stored? Obviously, session variables are used on the server side, so these session variables must be stored on the server side. By default, session variables are saved in ordinary files on the server (you can also configure it yourself and use a database to save it, you can Google it). The session ID acts like a key. Find the session in the file where the session is saved on the server side. Session variables corresponding to the ID, such as a list of purchased items.
Then the entire process of session control may look like this. When a user logs in or browses a page of a site for the first time, the site will generate a PHP session ID and send it to the client (browser) through a cookie. When the user clicks on another page on the site, the browser begins connecting to this URL. Before connecting, the browser will first search for locally saved cookies, and if there are any cookies related to the URL being connected, it will be submitted to the server. Just when logging in or connecting for the first time, a cookie related to the URL of the website (saved session ID) has been generated, so when the user connects to the site again, the site can identify the user through this session ID. The session variable related to this session ID is taken out of the server's session file to maintain continuity between transactions.
Next we understand the next two important concepts: cookie and session
About cookie maintenance and life cycle
The cookie is created on the server side and written back to the client browser. The browser receives the instruction to write the cookie in the response header and stores it in the local temporary folder.
A cookie file is created, which stores your cookie content. The cookie content is stored in the form of key-value pairs, and both the key and value can only be strings. For example:
File: Cookie:administrator@localhost/
Content format: voteID100101localhost/15361167667230343893360385046430343691*
Creation of cookies:
Note: The cookie header must be sent before other headers, otherwise it will have no effect (this is a cookie limitation, not a PHP limitation). The cookie value is automatically URL-encoded when sending the cookie and automatically decoded when retrieved (to prevent URL encoding, use setrawcookie() instead).
Cookie maintenance:
Cooke has four identifiers: cookie name, domain, path, and secure tag. To change the value of this cookie in the future, you need to send another Set-Cookie header with the same cookie name, domain, path, which will be replaced by a new
to overwrite the original cookie value. However, changing just one of these options will create a completely different cookie, such as just changing the name value.
Cookie expiration time:
You can set the expiration time. If not set, it will be at the session level, that is, it will disappear when you close the browser. When the cookie is created, it contains an expiration date, and this expiration date is associated with the cookie identified by name-domain-path-secure. To change a cookie's expiration date, you must specify the same combination. When changing the value of a cookie, you do not have to set the expiration date each time because it is not part of the cookie's identifying information. For example:
The expiration date on the cookie does not change because the cookie identifier is the same. In fact, the cookie's expiration date will not change unless you manually change it. This means that within the same session, a session cookie can become a persistent cookie (one that can exist across multiple sessions), but not vice versa. In order to change a persistent cookie into a session cookie, you must delete the persistent cookie. This can be achieved by setting its expiration date to a certain time in the past and creating a session cookie with the same name.
It is important to remember that the expiration date is verified based on the system time on the computer the browser is running on. There is no way to verify whether the system time is synchronized with the server time, so this setting will cause errors when there is a difference between the server time and the system time of the browser.
Cookies are automatically deleted:
Cookies will be automatically deleted by the browser, usually for the following reasons:
Session cookie (Session cookie) will be deleted when the session ends (browser is closed)
Persistent cookies will be deleted when the expiration date is reached, such as:
About session maintenance and life cycle
Session is a server-side storage space maintained by the application server. When the user connects to the server, a unique session ID will be created and generated by the server. The session ID is used as the identifier to access the server-side Session storage space. During the session , the unique sessionID assigned to the client, used to identify the current user and distinguish it from other users. Accept each access request through SessionID to identify the current user, track and maintain the user's specific information, and session variables, which can store numeric or text information in the session. For example, session_name. This information is saved on the server side. Of course, the session ID can also be saved in the database as session information for session persistence. This can track the number of user logins, online or not, online time, etc. to maintain the relationship between HTTP stateless things. The content storage of session is a list of key-value pairs, and the key is a string type. The storage of session is more convenient, and the value can be an object.
During the session, the session will be saved in two files on the client and server respectively. The client can save the sessionID in cookie mode (the default saving method) or pass it in the form of a url string. The server side is generally saved in the specified session directory in the form of text. On the server side, we can control which storage method the client uses through session.use_cookies. If it is defined as a cookie storage method, we can control the validity period of the cookie stored on the client through session.cookie_lifetime (default value 0, cleared when closing the browser). If the client uses a cookie to save the session ID, use a "temporary" cookie to save it (the name of the cookie is PHPSESSID. You can learn detailed information through Firebug. You can change the name through php.ini session.name) , when the user submits the page, this SessionID will be submitted to the server to access the session data. This process does not require developer intervention.
Session creation:
Note: This function has no parameters and the return value is true. If cookie-based sessin is used, there cannot be any output before session_satrt(), including blanks
If session.auto_start=1 is enabled in php.ini, session_start() will be executed on each page. No manual setting is required. This option is off by default. After it is enabled, objects cannot be placed in the session.
Session ID:
User session unique identifier, a randomly generated string, unique and random. Mainly used to distinguish session data of other users. When a user visits a web page for the first time, PHP's session initialization function call will assign a unique ID to the current visiting user, also called session_id.
Get session_id():
session data:
We call the user status information that needs to be saved through the session user session data, also known as session data. Generally, it is the corresponding $_SESSION data within the current session life cycle. Once session_start() is called to initialize the session, it means the beginning of a session life cycle. That is to say, it is announced that you can use related function operations $_SESSION to manage session data. The data generated by this session life cycle is not written to the session file in real time, but is stored in memory through the $_SESSION variable. $_SESSION is a global variable of type Array, which maps the session data of the session life cycle and is stored in memory. When the session is initialized, data is read from the session file and filled in the variable. At the end of the session (life cycle), write the $_SESSION data back to the session file.
Register a session variable:
From PHP4.1 onwards, session variables are stored in the super global array $_SESSION. To create a session variable, just set an element in the array, such as:
Log out Session variable/destroy session:
session_unset(); //Multiple releases. Release all variables registered in the session file
#In the session life cycle, log out all session data from the current session and make $_SESSION an empty array. The difference between it and unset($_SESSION) is that unset directly deletes the $_SESSION variable and releases memory resources; another difference is that session_unset() can only operate the $_SESSION array during the session life cycle, while unset() operates on the entire page ( page) life cycle can operate the $_SESSION array. session_unset() also does not perform any IO operations and only affects the $_SESSION array.
$_SESSION=array(); //Multiple releases, release all variables registered in the $_SESSION parameter
session_destroy();
#After using a session, you should first log out all variables, then call this function to end the current session, clear all resources in the session, and delete the session file on the server. This function will not unset (release) and the current session Session-related global variables will not delete the client’s session cookie
#If session_start() initializes a session, it will log out a session. It means that the session life cycle is over. After the session life cycle is completed, session_unset and $_SESSION['domain'] will not be able to operate the $_SESSION array, but the $_SESSION array can still be operated by functions such as unset(). At this time, the session means is undefined, and $_SESSION is still a global variable, and they are out of the mapping relationship.
Log out of the session through session_destroy(). In addition to ending the session life cycle, it will also delete the session file but will not affect the current $_SESSION variable. That is, it will generate an IO operation.
Remarks:
1. PHP’s default session is based on cookies. If you want to delete cookies, you must use the setcookie() function
2. The difference between session_unset() and unset() functions:
In the session life cycle, session_unset() logs out all session data from the current session, making $_SESSION an empty array. The difference between it and unset($_SESSION) is that unset directly deletes the $_SESSION variable and releases memory resources; another difference is that session_unset() can only operate the $_SESSION array during the session life cycle, while unset() operates on the entire page ( page) life cycle can operate the $_SESSION array. session_unset() also does not perform any IO operations and only affects the $_SESSION array.
Session lifetime: Session expiration time and expired recycling mechanism
We call the period from initializing the session to logging out of the session the session life cycle
By default, php will save the session in the directory set by session.save_path in the php.ini configuration. The file name is like this: sess_ves0d7uvdsab9k6sig73mnn592. Each file corresponds to a session. The session file format is roughly as follows:
Set the life cycle of SESSION:
PHP session is based on cookies, so to set the session life cycle, you must first set the cookie expiration time. Because when the client (such as a browser) logs in to the website, to see if the SESSION is useful, first check whether the client has a COOKIE, and then use the SESSION ID in the COOKIE to find the file on the server.
In fact, PHP5 Session also provides a function session_set_cookie_params(); to set the lifetime of PHP5 Session. This function must be called before the session_start() function is called:
On the server side, how does PHP determine whether the session file has expired?
If the "last modification time" to "now" exceeds session.gc_maxlifetime (default is 1440) seconds, that is to say, the file has not been modified within the time set here, the session file is considered Expired. Since php5's session adopts a passive recycling mechanism, the expired session file will not disappear by itself. Instead, the expired session will be processed by triggering "recycling". Then the next time the session is recycled, if the file has not been changed. After that, the session file will be deleted (the session will expire).
When does session recycling occur?
By default, there is a 1% probability of recycling for every php request, so it may be simply understood as "there may be a recycling probability for every 100 php requests." This probability is controlled by the following parameters:
These two together are the probability of starting the Gabadge Collection (gc) process management, when the session is first activated (session_start()). Track session information files after Gabadge Collection is started. Its startup probability is session.gc_probability/session.gc_divisor. In other words, not every session information file is 100% treated as garbage by the system. If you close the browser directly, the session information file will remain on the server in many cases. If you change the probability to 100%, although the Gabadge Collection will be activated 100%, it will add load to the server and it will be lost. The meaning of GC itself is over.
Additional instructions:
1. Assume that session.gc_maxlifetime=1440 in this case. If a session file was last modified 1440 seconds ago, then the session will still be valid before the next recycling (1/100 probability) occurs;
2. If your session uses session.save_path to save the session elsewhere, the session recycling mechanism may not automatically process expired session files. At this time, you need to delete expired sessions manually (or crontab) regularly: cd /path/to/sessions; find -cmin +24 | xargs rm;
3. Note that when the number of server-side session files is not effectively recycled and gradually grows to GB or larger, your site may become slower and slower when accessing sessions. This is more common when logging in and out of the site. will be affected;
4. When we write logs, weekly reports, monthly reports, etc. at the last moment of submission, sometimes messages such as "Invalid operation, please log in and try again" will appear. The reason is self-evident. It may be that the session has expired. gc clears session files that have "timed out".
Some special cases:
Because the recycling mechanism will check the "last modification time" of the file, so if a session is active, but the content of the session has not changed, then the corresponding session file has not changed, and the recycling mechanism will consider this A session that has not been active for a long time will be deleted. This is something we don’t want to see. We can solve this problem by adding the following simple code:
Understand the differences and connections between cookies and sessions
Similar points: Both can solve the problem of HTTP statelessness, so that the same client can save and set information and establish connections between requested things in multiple requests to visit the website.
Difference: Simply put, cookie information is stored on the client side, and session information is stored on the server side.
Session uses key-value pairs, which means that the ID is stored on the client side, and the value is placed on the server side. The user's ID is used to find the corresponding value on the server. In this way, the value is placed on the server side, and there is a time limit. , the server automatically recycles/releases it when the time is up.
Cookies have two methods. One method is to save the value in the browser's variable and end when the browser is closed. The other method is to save it on the hard disk. As long as the time does not expire, it can be used next time. use.
Contact: When the client uses the SessionID saved based on Cookie, the SessionID is generally saved in the cookie.
Note: Cookies are shared between browsers with the same core. Browsers with different cores are not shared, such as Firefox and IE (the storage locations are different, and of course they are not shared). Browsers with different kernels cannot share cookies and will also generate different sessionids.
Question 1: Why does the session fail after disabling cookies?
First of all, let me explain: session does not necessarily have to rely on cookies, but PHP's default client sessionid is saved based on cookies.
At this point, I think you should also understand that the default session saving method of PHP client is based on cookies, so once the client disables cookies, the session will be invalid across pages. I don’t know if this description is appropriate. In layman’s terms To make a stateless thing stateful, you can only compare both sides. If the SessionID is saved in cookie mode, the comparison conditions on the client side will be placed in the cookie. Therefore, if the client disables cookies, the session will be will then become invalid. PHP's session client ID generally has two storage methods: cookie and url. If the session ID is saved in a cookie, you can see that there is a PHPSESID variable in the browser's cookie (can be viewed through firefox). If it is passed by URL (it is recommended to use hidden form delivery), you can see the URL in the form: index.php?PHPSESID=ves0d7uvdsab9k6sig73mnn592. For example:
demo2.php
session_start();
echo 'session value is'.$_SESSION['blog'];
?>
Running the above code, if the client cookie is normal, we can print out the value of $_SESSION['blog'] in demo2.php as: http://blog.jb51.net. However, now if you manually disable the client's cookies and then run the instance, you may not get the result. Because the default client sessionid saving method cannot read the sessionid of the previous page after crossing a page, when session_start(); is executed; a session file will be generated, and the corresponding session id will be generated correspondingly. Use this session id It is impossible to get out the variables in the first session file mentioned earlier, because this session id is not the "key" to open it. If you add the code session_id($sessionid); before session_start();, a new session file will not be generated, and the session file corresponding to this id will be read directly. To put it simply, get the session id on the previous page, and then find a way to pass it to the next page. Add the code session_id (passed sessionid) before the session_start(); code on the next page; For example:
demo2.php
$sid = $_GET['sid'];
if(!empty($sid)){
session_id($sid);
session_start();
}else{
session_start();
$sid = session_id();
}
$id = $_POST['id'];
$key = 'poll_'.$id;
if($id!=''){
echo $key = 'poll'.$id;
if(!empty($_SESSION[$key])){
$_SESSION[$key]=$_SESSION[$key] + 1;
}else{
$_SESSION[$key]=1;
setcookie($key ,$id+1,time()+3600*24);
}
echo '<script>alert("success");javascript:location.href="demo.php?sid='.$sid.'";</script>';
}else{
echo '<script>alert("failed!ID Null");javascript:history.back(-1);</script>';
}
?>
除此之外,我们还可以将客户端PHPSESID存放到文件中,如:
demo2.php
$fp=fopen("D:tmpwebsid.txt","r");
$sid=fread($fp,1024);
fclose($fp);
session_id($sid);
session_start();
print_r($_SESSION);
当客户端禁用cookie,可以通过以下几种方式改变session对客户端cookie的依赖,使session抛开客户端cookie:
1、设置php.ini中的session.use_trans_sid = 1或者编译时打开打开了--enable-trans-sid选项,让PHP自动跨页传递session id。当session.use_trans_sid为有效时,ession.use_only_cookies一定要设置为无效0。
2、手动通过URL传值、隐藏表单传递session id。
3、用文件、数据库等形式保存session_id,在跨页过程中手动调用。
PHP也提供一个函数:
说明:此函数给URL重写机制添加名/值对。 这种名值对将被添加到URL(以GET参数的形式)和表单(以input隐藏域的形式),当透明URL重写用 session.use_trans_sid 开启时同样可以添加到session ID。 要注意,绝对URL(http://jb51.net/..)不能被重写。此函数的行为由url_rewriter.tags php.ini 参数控制。
这样sessionID会跟在URL后面而且from中会出现sessionID的hidden值。
改变session客户端ID保存方式:
session.use_cookies //控制客户端保存SessionID时使用哪一种方式,当它为“1”时,就说明启动了session cookie(初始值为1)
可以使用上面我们提到的函数来查询得到目前的session id:echo $_COOKIE["PHPSESSID"];
但是,如果client的浏览器不支持cookie的话,即使session.use_cookies这个参数的值等于“1”,用上述的查询也只会得到null。
php.ini中两个和该选项相关的配置参数:
Note: If the customer's browser supports cookies, it is strongly recommended to "session.use_only_cookies = 1". When session.use_only_cookies is valid, even if you want to pass the session id through the URL, it will be considered invalid, which can reduce Possibility of being attacked via sessionid. The above two configurations are set in the php code page:
The session is lost in IE, and a new session ID will be generated every time the page is refreshed (Firefox browser is normal)
If this problem occurs on your server or site, please configure the session.cookie_path website domain correctly. If the configuration is incorrect, it may cause the following common failures:
(1) Each PHPSESSID on the client will have a one-to-one correspondence on the server to generate an independent session record and store it on the server, so the server-side session file redundancy will increase (when the GC recycling mechanism is abnormal, site access When the quantity is large)
(2) Sites that use sessions to record relevant information may have problems when accessed under browsers other than Firefox (Chrome has not been tested), for example: shopping carts cannot record purchased items, site login fails, etc.
Supplement: If all browser access refreshes generate new sessionIDs, please check whether cookies are disabled on the client.
Simple example of session
Use session to prevent repeated submission of forms:
Login verification example code using session method:
Example code for login verification using cookie method:
vote.php Voting action execution page
$tokenKey = $_SESSION['tokenKey'];
if($_POST['tokenKey'] != $tokenKey){ //Determine whether the random code is the same as the previous page
echo "<script>alert('Please vote again!');location.href='list.php';</script>"; //Invalid random code
exit;
}else{
Execute voting operation;
Clear the random code stored in the session
}
Answers cannot be saved. . . If the user turns off cookies, both the session and the cookie will become invalid
But the session in php does not necessarily require cookies
Find the session.use_trans_sid value in php.ini and set it to 1. Restart the server. After disabling cookies, the sessionid can still be saved. Can it be saved?
in client memory
The difference between session and cookie:
1: If the session content is stored in a file, where is the file?
Answer: Session.save_path = "D:/tmp",
If not specified, it will be placed by default C:/windows/temp, the default "/tmp" directory under Linux
2: The relationship between cookie and session
Answer: Cookie can be used to store session_id
tangram_guid_1357433851419 Idea: If cookies are disabled by the browser, What should I do?
3: session.use_cookies = 1
This option tells the server: use cookies to store session_id
session.use_only_cookies = 0, whether to only use cookies to transmit session_id
session.use_trans_sid = 1 // Set the address bar session_id
4: The relationship between cookie and session
Answer: Cookie is used to store and transfer session_id
If cookies are disabled, can session be used?
Answer: Yes, secondly , we can use javascript to detect whether the browser supports cookies, and prompt the user to open cookies
5: What is the default life cycle of session?
Answer: It will become invalid when the browser is closed. Reason: Because the session_id exists in the cookie, and By default, the cookie fails when the browser is closed.
6: How to set the session life cycle to 30 minutes?
Answer: session.cookie_lifetime = 1800 php.ini to set it
7: localhost/0415/set .php, set session,
Excuse me, under which paths does the session value take effect??
Answer: Wherever the cookie used to pass session_id takes effect, the session takes effect
7.5: The cookie passed in session_id takes effect Where does it take effect?
Answer: The default is to take effect in the '/' directory
Difference: The cookie takes effect in the set directory by default, and the session takes effect in the / directory by default
8: If the setting passes session_id What is the valid path of the cookie?
Answer: session.cookie_path = /, you can set it here