In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-28 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article introduces the relevant knowledge of "detailed explanation of Session and Cookie in PHP". In the operation of actual cases, many people will encounter such a dilemma, so let the editor lead you to learn how to deal with these situations. I hope you can read it carefully and be able to achieve something!
This paper introduces PHP session control, and mainly expounds the following points:
Background / concept of session control
Maintenance and life cycle of cookie (effective time)
Maintenance and life cycle of session (recycling mechanism)
The difference and relation between cookie and session
Question1: why does session fail when cookie is disabled?
The session is lost in the problem 2:IE browser. Every time the page is refreshed, a new sessionID will be generated (Firefox browser is normal)
Simple examples of session and cookie
Understand the concept of conversation control
To understand a concept, you need to understand its background and reasons. Here, the WEB environment and its HTTP protocol are introduced. The background of session control:
Students who have read the materials related to the HTTP protocol will know that the HTTP protocol is a protocol for communication between the WEB server and the client (browser). It is a stateless protocol, which means that the http request data will not be maintained, and the http request is independent and not persistent. In other words, the HTTP protocol does not have a built-in mechanism to maintain the state 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 come from the same user.
As a result, we will feel very strange, usually when we are shopping in forums or e-commerce sites, as long as we are in this site, no matter how we jump from one page to another, the website will always remember who I am. Like telling you what you bought. How to do this, I guess you have guessed, this is the use of HTTP session control. Track a variable in the website, through the tracking of the variable, establish a relationship between multiple requests, and display different content and different pages according to authorization and user identity.
PHP Session session Control:
PHP's session session is driven by a unique session ID, which is an encrypted random number generated by PHP and saved on the client during the lifetime of the session. We know that the only place where the client (that is, the browser) stores data is cookie, so the session ID of PHP is generally stored in the cookie of the user's machine. After learning about cookie, we know that browsers can disable cookie, so that the session will become invalid. So there is another mode of PHP session control, which is to pass the session ID in URL. If we pay a little attention when browsing the website, some URL has a string that looks like a random number, then it's probably session control in the form of URL.
At this point, some people may have doubts, the client is only saving a session ID, so where are the session variables stored in the session control, such as the list of items you bought while shopping, where are they stored? Obviously, session variables are used on the server side, so they must be stored on the server side. By default, session variables are saved in a normal file on the server (you can also configure to use a database to save them, and you can Google them). The session ID acts like a key. Find the session variables corresponding to the session ID in the file where the session is saved on the server, such as a list of purchased items.
Then the whole 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 generates a PHP session ID and sends it to the client (browser) through cookie. When the user clicks on another page of the site, the browser starts to connect to the URL. Before connecting, the browser searches for the locally saved cookie, and if there is any cookie in the cookie related to the URL being connected, submit it to the server. Just when logging in or connecting for the first time, a cookie (saved session ID) related to the website URL has been generated, so when the user connects to the site again, the site can identify the user through the session ID and extract the session variables related to the session ID from the session file of the server, thus maintaining the continuity of transactions.
Next, let's look at two important concepts: cookie and session.
On the maintenance and Lifecycle of cookie
The cookie is created on the server side and written back to the client browser, and the browser receives the instruction in the response header to write cookie in the local temporary folder.
Create a cookie file that stores your cookie content. Cookie content is stored as a key-value pair, and both keys and values can only be strings. For example:
File: Cookie:administrator@localhost/
Content format: voteID100101localhost/15361167667230343893360385046430343691*
Creation of cookie:
The copy code is as follows:
The setcookie () function sets cookie. The function prototype is as follows
Setcookie (name, value, expire, path, domain)
Note: the cookie header must be sent before sending other headers, otherwise it will be invalid (this is the restriction of cookie, not the restriction of PHP). When sending cookie, the value of cookie is automatically URL-encoded and automatically decoded when retrieved (to prevent URL encoding, use setrawcookie () instead).
Maintenance of cookie:
Cooke has four identifiers: the name,domain,path,secure tag for cookie. 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 take a new
To override the value of the original cookie However, simply changing one of these options will create a completely different cookie, such as just changing the name value.
Cookie failure time:
You can set the expiration time, if not, it is session-level, that is, closing the browser will disappear. When the cookie is created, it contains the expiration date, which is associated with the cookie identified by name-domain-path-secure. To change the expiration date of a cookie, you must specify the same combination. When changing the value of a cookie, you do not have to set the expiration date every time, because it is not part of the cookie identification information. For example:
The copy code is as follows:
Setcookie (vote, $id+1,time () + 3600mm 24)
Setcookie (vote,$id)
The expiration date on cookie has not changed because the identifier of cookie is the same. In fact, only you manually change the expiration date of the cookie, otherwise the expiration date will not change. This means that in the same session, a session cookie can become a persistent cookie (one that can exist in multiple sessions), and vice versa. To change a persistent cookie into a session cookie, you must delete the persistence cookie, which can be achieved by setting its expiration date to a certain time in the past and then creating a session cookie with the same name.
It is important to remember that the expiration date is verified against the system time on the computer on which the browser is running. There is no way to verify that the system time is synchronized with the server time, so this setting can go wrong when there is a difference between the server time and the browser's system time.
Cookie automatically deletes:
Cookie is automatically deleted by browsers for the following reasons:
Session cooke (Session cookie) is deleted at the end of the session (browser closed)
Persistent cookie (Persistent cookie) is deleted when the expiration date is reached, such as:
The copy code is as follows:
Setcookie ("vote", ", time ()-3600)
If the cookie limit in the browser is reached, the cookies will be deleted to create space for the new cookies.
On the maintenance and Lifecycle of session
Session is a server-side storage space maintained by the application server. When a user connects to the server, a unique sessionID is created by the server, and the sessionID is used as an identifier to access the server-side Session storage space. During the session, the unique sessionID assigned to the client is used to identify the current user and distinguish it from other users. Through SessionID to accept each visit request, so as to identify the current user, track and maintain the specific data of the user, as well as session variables, you can store digital or text data in session. For example, session_name. This information is stored on the server side. Of course, sessionID can also be saved as session information in the database for session persistence. In this way, you can track the number of times you log in, whether you are online or not, online time, and so on, so as to maintain the relationship between HTTP stateless things. The content store of session is a list of key-value pairs, the key is a string type, the storage of session is more convenient, and the value can be an object.
During a session session, session is saved on the client side and server side, respectively. The client side can be sessionID saved in cookie mode (the default save method) or passed through a url string. The server side is generally saved as text in the specified session directory. On the server side, we can use session.use_cookies to control which save method is used by the client. If it is defined as the cookie save method, we can control the validity of the cookie saved on the client through session.cookie_lifetime (the default value is 0, which is cleared when the browser is closed). If the client uses cookie to save the sessionID, then use the "temporary" cookie save (the name of the cookie is PHPSESSID, through Firebug you can learn more information, the name you can change through php.ini session.name), when the user submits the page, the SessionID will be submitted to the server to access session data. This process does not require the intervention of developers.
Creation of Session:
The copy code is as follows:
Session_start () / / start a session and return an existing session
Function: initializes the Session, which also marks the beginning of the session life cycle. To use session, you must initialize a session environment, somewhat similar to the OOP concept of calling a constructor to create an object instance. The session initialization operation declares a global array $_ SESSION that maps session data stored in memory. If the session file already exists and the session data is saved, session_start () reads the session data and fills it in $_ SESSION to start a new session life cycle.
Note: this function has no arguments and the return value is true. If you use cookie-based sessin, you cannot have any output, including white space, before session_satrt ().
If session.auto_start=1 is turned on in php.ini, session_start () is executed on each page without manual setting. This option is off by default, and objects cannot be placed in the session when enabled.
Session ID:
User session unique identifier, a randomly generated string, with uniqueness and randomness. Mainly used to distinguish the session data of other users. When the user visits the web page for the first time, the session initialization function call of php assigns the current visiting user a unique ID, also known as session_id.
Get session_id ():
The copy code is as follows:
Echo $_ COOKIE ['PHPSESSID'].'
Echo $_ Cookie [session _ name ()].''
Echo session_id ().
Session data:
We call the user state information that needs to be saved through session as user session data, also known as session data. Typically in the current session life cycle, the corresponding $_ SESSION data. Once session_start () is called to initialize session, it means that a session life cycle has begun. That is, it is announced that you can use the related function operation $_ 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 that maps the session data of the session life cycle and is stored in memory. When session initializes, read the data from the session file and fill it in the variable. At the end of the session (life cycle), write the $_ SESSION data back to the session file.
Register a session variable:
Since PHP4.1, session variables are saved in the super global array $_ SESSION. To create a session variable, simply set an element in the array, such as:
The copy code is as follows:
$_ SESSION ['domain'] = blog.jb51.net
$_ SESSION ['poll'] = $_ sessions [poll] + 1
Use a session variable:
The copy code is as follows:
Echo $_ SESSION ['blogdomain']; / / print out blog.jb51.net. Before using a session, you must start a session using the session_start () function.
Log out of the Session variable / destroy the session:
The copy code is as follows:
Unset ($_ SESSION); / / destroy a single session variable
For example: unset ($_ SESSION ['blogdomain'])
The function # unset ($_ SESSION) destroys the global variable $_ SESSION, and there is no feasible way to restore it. Users can no longer register the $_ SESSION variable, so this function is not available.
Session_unset (); / / multiple releases. Release all variables logged in the session file
# in the session lifecycle, log out all session data from the current session, leaving $_ SESSION as an empty array. It differs from unset ($_ SESSION) in that unset directly deletes the $_ SESSION variable to free memory resources; another difference is that session_unset () can only operate on the $_ SESSION array in the session life cycle, while unset () can operate on the $_ SESSION array throughout the page life cycle. Session_unset () also does not do any IO operations, affecting only the $_ SESSION array.
$_ SESSION=array (); / / multiple releases, releasing all variables logged in the $_ SESSION parameter
Session_destroy ()
When you finish using a session, you should first log out all variables, then call this function to end the current session, empty all resources in the session, and delete the session file on the server. This function does not unset (release) global variables related to the current session, nor does it delete the client's session cookie
# Let's say session_start () initializes a session and it logs out of a session. It means the session life cycle is over. After the session life cycle is completed, session_unset, $_ SESSION ['domain'] will not be able to operate on the $_ SESSION array, while the $_ SESSION array can still be manipulated by functions such as unset (). At this point, session means that it is undefined, while $_ SESSION is still a global variable, and they are out of the relational mapping relationship.
Logging out of session with session_destroy () removes the sesion file in addition to ending the session life cycle, but does not affect the current $_ SESSION variable. That is, it produces an IO operation.
Note:
1. Php's default session is based on cookie. If you want to delete cookie, you must use the setcookie () function.
2. The difference between the session_unset () and unset () functions:
During the session life cycle, session_unset () logs out all session data from the current session, leaving $_ SESSION as an empty array. It differs from unset ($_ SESSION) in that unset directly deletes the $_ SESSION variable to free memory resources; another difference is that session_unset () can only operate on the $_ SESSION array in the session life cycle, while unset () can operate on the $_ SESSION array throughout the page life cycle. Session_unset () also does not do any IO operations, affecting only the $_ SESSION array.
Session Life cycle (session lifetime): Session failure time and expiration recovery mechanism
The period between initializing session and logging out of session is called the session lifecycle.
By default, php saves the session in the directory set by session.save_path in the php.ini configuration, and the file name looks like this: sess_ves0d7uvdsab9k6sig73mnn592. Each file corresponds to a session (session). The session file format is roughly as follows:
The copy code is as follows:
Poll_200 | iRAPR 1% pollication 100 | iRom 3; / / # variable name | Type: length: value
Set the lifecycle of SESSION:
Php session is based on cookie, so to set the life cycle of session, you must first set the failure time of cookie. Because when the client (such as the browser) logs in to the website, whether SESSION is useful, first find out whether the client has COOKIE, and find the file on the server through the SESSION ID in COOKIE.
The copy code is as follows:
Session_start ()
$lifeTime = 24 * 3600; / / keep for one day
Setcookie (session_name (), session_id (), time () + $lifeTime, "/")
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:
The copy code is as follows:
$lifeTime = 24 * 3600; / / keep for one day
Session_set_cookie_params ($lifeTime)
Session_start ()
On the server side, how does php determine whether the session file is out of date?
The copy code is as follows:
Session.gc_maxlifetime = 1440 (initial value)
# set session survival time (in seconds). After each GC startup, the unix time of the last access to the session file is obtained through stat, and the file will be deleted if the current time minus the last access time of the file is greater than session.gc_maxlifetime.
If the "last modification time" to "now" exceeds the 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 to have expired. Because php5's session uses a passive recycling mechanism, expired session files will not disappear by themselves, but by triggering "recycling" to deal with expired session, then the next session recycling If the file has not been changed, the session file will be deleted (session will be out of date).
When does session recycling occur?
By default, there is a 1% probability of recovery for every php request, so it may be simply understood as "every 100 php requests may have a recovery probability." This probability is controlled by the following parameters:
The copy code is as follows:
Session.gc_probability = 1 (initial value)
Session.gc_divisor = 100 (initial value)
# these two functions determine the probability of enabling GC. The default is 1x1000. In other words, GC Recycling session is started for every thousand user requests. The GC process should not be started too frequently. The website visited too frequently and the website with a large amount of concurrency can reduce the startup frequency of PHP GC. Recycling session by PHP GC will reduce the execution efficiency of php.
Together, these two are used to start the Gabadge Collection (gc) process management probability when session is initialized (session_start ()). Track the session information file after Gabadge Collection starts. The start-up probability is session.gc_probability/session.gc_divisor. In other words, not every session information file is treated as rubbish by the system. If you close the browser directly, the session information file is left on the server in many cases. If the probability is changed to 100%, although Gabadge Collection is started 100%, it will add load to the server and lose the meaning of GC itself.
Supplementary note:
1. Suppose this is the case, session.gc_maxlifetime=1440. If the last modification time of a session file is 1440 seconds, then the session will still be valid before the next collection (the probability of 1100).
2. If your session uses session.save_path to save session,session recycling somewhere else, it may not automatically process expired session files. In this case, you need to delete expired session:cd / path/to/sessions; find-cmin + 24 manually (or crontab) regularly. | xargs rm
3. Note that when the number of session files on the server side is not effectively recycled, it may be slower and slower for your site to access session when it gradually grows to GB or greater, and it is more common that site login and logout will be affected.
4. When we finally submit the log, weekly and monthly reports, sometimes there will be messages such as "invalid operation, please log in and try again". The reason is self-evident. The reason may be that session is invalid and gc clears those session files that have "timed out".
Some special cases:
Because the recycling mechanism checks the "last modification time" of the file, if a session is active but the contents of the session have not changed, then the corresponding session file has not changed, and the recycling mechanism will delete it as a session that has not been active for a long time. We don't want to see this, and we can solve this problem by adding the following simple code:
The copy code is as follows:
/ / the code will try to modify the session every 120 seconds.
Understand the difference and relationship between cookie and session
Similarities: can solve the HTTP stateless problem, so that the same client in the multiple requests to visit the site, can save, set up information, and establish connections between requests.
The difference: to put it simply, the information of cookie is saved on the client side, and the information of session is stored on the server side.
Session uses key-value pairs, that is, ID stores the client side, while the value is placed on the server side through the user's ID to find the corresponding value on the server. In this way, the value is placed on the server side. There is a time limit, and the server automatically collects / releases the value when the time expires.
Cookies has two methods, one is to save the value in the browser's variable, which ends when the browser is closed, and the other is to save it on the hard disk, as long as the time does not expire, it can be used next time.
Contact: when the client uses a SessionID saved based on Cookie, the SessionID is generally saved in cookie.
Note: cookie is shared among browsers with the same kernel, while different kernel browsers are not shared, such as Firefox and IE (different locations, of course, not shared). Different kernel browsers cannot share cookie, and different sessionid will be generated.
Question1: why does session fail when cookie is disabled?
First of all, let's make it clear that session does not have to rely on cookie, but the default client of php, sessionid, is saved based on cookie.
At this point, I think you should also understand that the default session client saving method of php is based on cookie, so once the client disables Cookie, the session spread will fail. I don't know if this description is appropriate. It is popular to say that stateless things should become stateful and can only be compared on both sides. If the SessionID is saved in cookie, the comparison conditions on the client side will be put in cookie, so the client side forbids cookie. Session will fail as well. Php's session client ID is generally saved in two ways: cookie and url. If you save session ID in cookie, you can see that there is a PHPSESID variable in the browser's cookie (which can be viewed through firefox). If it is passed by URL (it is recommended to use hidden form delivery), you can see the URL that looks like: index.php?PHPSESID=ves0d7uvdsab9k6sig73mnn592. For example:
The copy code is as follows:
Demo1.php
Run the above code, under the normal condition of the client cookie, 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 cookie and then run the instance, you may not get the results. Because the default client-side sessionid save mode after the spread, can not read the previous page of sessionid, when the implementation of session_start (); will generate another session file, corresponding to the corresponding sessionid, with this sessionid can not take out the variables in the first session file mentioned earlier, because this sessionid is not the "key" to open it. If you add the code session_id ($sessionid) before session_start (); no new session file will be generated, but the session file corresponding to this id will be read directly. To put it simply, get the sessionid on the previous page, and then find a way to pass it to the next page, in the session_start () of the next page; add the code session_id (the passed sessionid) before the code; for example:
The copy code is as follows:
Demo.php
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.