The session mechanism in PHP

Source: Internet
Author: User
Tags session id setcookie cron script drupal


PHP in the cookie and session is our common two variables, one is the user client, one used in the server but their differences and how it works, let's take a look at the cookie and session mechanism principle.

Differences and linkages between cookies and session mechanisms

Specifically, the cookie mechanism uses a scheme that maintains state on the client. It is the storage mechanism of session state on the client side, and he needs the user to open the cookie support of the clients. The purpose of cookies is to resolve the problem of stateless defects in the HTTP protocol.

The session mechanism uses a solution that maintains state between the client and the server. At the same time, we also see that because of the server-side hold state of the scheme in the client also need to save an identity, so the session mechanism may need to use the cookie mechanism to achieve the purpose of preserving the identity. The session provides a convenient way to manage global variables

Session is for each user, the value of the variable is saved on the server, with a sessionid to distinguish which user session variable, this value is accessed by the user's browser when the server is returned, when the customer disables the cookie, This value may also be set to be returned to the server by get.

As far as security is concerned: when you visit a site that uses a session and create a cookie on your own machine, it is recommended that the session mechanism on the server side be more secure. Because it does not arbitrarily read the information stored by the customer.

Orthodox cookie distribution is implemented by extending the HTTP protocol, and the server prompts the browser to generate the appropriate cookie by adding a special line of instructions to the HTTP response header

From a Web server standpoint, all HTTP requests are independent of the previous request. This means that each HTTP response relies entirely on the information contained in the corresponding request.

The state management mechanism overcomes some of the limitations of HTTP and allows the relationship between network clients and server-side maintenance requests. The period during which this relationship is maintained is called a session.

Cookies are small pieces of text that the server stores on the local machine and are sent to the same server with each request. Ietfrfc2965httpstatemanagementmechanism is a generic cookie specification. The Web server sends cookies to the client using HTTP headers, and in the client terminal, the browser parses the cookies and saves them as a local file, which automatically binds any request from the same server to these cookies.

--------------------------------------------------------------------------------------------------------------- ----------------------------------------------------

Understanding the session mechanism

The session mechanism is a server-side mechanism that uses a hash-like structure (or perhaps a hash table) to hold information.

When a program needs to create a session for a client's request, the server first checks to see if the client's request contains a session ID-called SessionID, If a SessionID is already included, it indicates that the session was previously created for this client, and the server will follow SessionID to retrieve the session (if it is not retrieved, it may create a new one), if the client request does not contain SessionID, Creating a session for this client and generating a value for the Sessionid,sessionid associated with this session should be a string that is neither duplicated nor easily found to mimic the pattern, which SessionID will be returned to the client in this response to be saved.

This sessionid can be saved in a cookie-like manner, so that the browser can automatically play the logo to the server during the interactive process. Generally the name of this cookie is similar to Seeesionid, and. For example, WebLogic for Web application generation cookie,jsessionid=byok3vjfd75apnrf7c2hmdnv6qzcebzwowibyenlerjq99zwpbng!- 145788764, its name is Jsessionid.

Since cookies can be artificially banned, there must be other mechanisms that can still pass SessionID back to the server when the cookie is banned. A technique that is often used is called URL rewriting, which is to append SessionID directly to the URL path, and there are two additional ways, which are additional information as URL paths, in the form of http://...../xxx;jsessionid= byok3vjfd75apnrf7c2hmdnv6qzcebzwowibyenlerjq99zwpbng!-145788764

The other is appended to the URL as a query string, in the form of http://...../xxx?jsessionid=ByOK3vjFD75aPnrF7C2HmdnV6QZcEbzWoWiBYEnLerjQ99zWpBng!-145788764

These two ways for the user is no difference, but the server in the resolution of the way the process is different, the first way is also conducive to the SessionID information and normal program parameters to distinguish.

In order to maintain state throughout the interaction, the SessionID must be included after each client may request a path.

Another technique is called a form-hidden field. Is that the server automatically modifies the form, adding a hidden field so that SessionID can be passed back to the server when the form is submitted. such as the following form

will be rewritten before being passed to the client.

This technique is now less applied, and the very old IPlanet6 (the predecessor of the SunOne Application server) that the author has contacted has used this technique.

In fact, this technique can be replaced simply by applying URL rewriting to the action.

When we talk about the session mechanism, I often hear a misunderstanding that "as soon as you close the browser, the session disappears." In fact, you can imagine the membership card example, unless the customer actively to the store to sell cards, otherwise the store will not easily delete customer information. For the session is also the same, unless the program notifies the server to delete a session, or the server will remain, the program is generally in the user to do logoff the time to send a command to delete the session. However, the browser will never proactively notify the server before shutting down, so the server will not have the opportunity to know that the browser has been shut down, the reason for this illusion is that most of the session mechanism uses a conversation cookie to save SessionID, and after closing the browser this SessionID disappears, and once again the server will not be able to find the original session. If the cookie set by the server is saved to the hard disk, or if a device is used to overwrite the HTTP request header issued by the browser and send the original sessionid to the server, the original session can still be found by opening the browser again.

It is precisely because closing the browser does not cause the session to be deleted, forcing the server to set an expiration time for seesion, when the client last time to use the session more than the expiration time, the server can assume that the client has stopped the activity, The session is deleted to save storage space.

--------------------------------------------------------------------------------------------------------------- --------------------------------------------------------

Talking about the difference and connection between cookie and session by Jsessionid

In some polls and the like, we tend to ask everyone to vote only for the principle of fairness, in some web development there are similar situations, we usually use cookies, such as the following code:

Cookie[]cookies=request.getcookies ();
if (cookies.lenght==0| | Cookies==null)
Dostufffornewbie ();
has not been visited
Dostuffforreturnvisitor ();//has been visited

This is very easy to understand, to detect the existence of a cookie, if there is a description has been run to write the cookie code, but after running the above code, whenever the results are executed dostuffforreturnvisitor (), Through the Control Panel-internet options-Settings-view file but always do not see the generated cookie file, strange, the code is clearly not a problem, but since there is a cookie, then show it.

Cookie[]cookies=request.getcookies ();
if (cookies.lenght==0| | Cookies==null)
Out.println ("Hasnotvisitedthiswebsite");
for (inti=0;i<cookie.length;i++)
Out.println ("CookieName:" +cookies[i].getname () + "Cookievalue:" +
Cookie[i].getvalue ());

Operation Result:

Why do cookiename:JSESSIONIDcookievalue:KWJHUG6JJM65HS2K6 have cookies? Everyone knows that HTTP is a stateless protocol, and every time a customer reads a Web page, the server opens a new session. And the server does not automatically maintain the customer's contextual information, then how to implement the shopping cart in the online store, the session is a mechanism to save context information, it is for each user, the value of the variable is stored on the server side, through the sessionid to distinguish between different customers, The session is based on a cookie or URL rewrite, which is implemented by default using a cookie, and the system creates an output cookie called Jsessionid, which we call Sessioncookie to differentiate Persistentcookies, That is what we usually call cookies, note that Sessioncookie is stored in the browser memory, not written to the hard disk, which is the jsessionid we just saw, we usually do not see Jsessionid, But when we disable the browser cookie, the Web server passes the SessionID in the URL rewrite, and we can see strings like sessionid=kwjhug6jjm65hs2k6 in the address bar.

Understand the principle, we can easily distinguish between persistentcookies and sessioncookie of the difference, online those about the security of the discussion is also at a glance, Sessioncookie for a session, Session end Sessioncookie disappears, and Persistentcookie is only a piece of text (usually encrypted) that exists on the client's hard disk, and may be subject to cookie spoofing and cross-site scripting attacks against cookies. Nature is less safe than Sessioncookie.

Usually Sessioncookie can not be used across windows, when you open a new browser window into the same page, the system will give you a new SessionID, so that the purpose of our information sharing is not reached, At this point we can first save the SessionID in the Persistentcookie, and then read it in a new window, we can get the last window SessionID, This enables cross-window sessiontracking (session tracking) through the combination of Sessioncookie and Persistentcookie.

In some web development books, it is often just a simple way to send the session and cookie as two parallel HTTP messages, sessioncookies on the server side, Persistentcookie on the client, But the session is based on the cookie, understand the relationship between the two and the difference, we will not be difficult to choose the right technology to develop webservice.

Then I read a session about the thorough understanding of PHP

1.session.save_handler = Files

* 1. Session_Start ()
1. Session_Start () is the beginning of the session mechanism, it has a certain probability to turn on garbage collection, because the session is stored in the file,
PHP itself garbage collection is not valid, the session of the recycling is to delete files, this probability is based on the configuration of PHP.ini,
However, some systems are session.gc_probability = 0, which means that the probability is 0, but instead of using a cron script to implement garbage collection.

session.gc_probability = 1
Session.gc_divisor = 1000
Session.gc_maxlifetime = 1440//Expiration time default 24 minutes
The probability is session.gc_probability/session.gc_divisor result 1/1000,
It is not recommended to set too small because the session garbage collection is required to check whether each file is out of date.
Session.save_path =//As if different systems are not the same by default, one setting is "N;/path"
This is a random tiered storage, this kind of word, garbage collection will not work, need to write their own scripts

2. The session will determine if there is currently $_cookie[session_name ()];session_name () to return the COOKIE key value that holds the session_id.
This value can be found from php.ini = PHPSESSID//default value PHPSESSID

3. If it does not exist, it generates a session_id and then passes the generated session_id as the value of the cookie to the client.
is equivalent to performing the following cookie operation, note that this step performs a setcookie () operation, the cookie is sent in the header,
There is no output before this, PHP has another function session_regenerate_id () If you use this function, you cannot have output before.

Setcookie (Session_name (),
session_id (),
session.cookie_lifetime,//Default 0
session.cookie_path,//default '/' current program and directory are valid
session.cookie_domain,//default is empty

         4. If there is session_id = $_cookie[session_name];
            then go to session.save_path the specified folder to find the name ' Sess_ '. session_id () file.
            Read the contents of the file to deserialize and put it in $_session
     * 2. Assign a value of $_session
      For example add a value $_session[' test '] = ' blah '; then this $_session will only be maintained in memory, At the end of the script execution,
writes the value of $_session to the folder specified in session_id and then closes the related resource .      this stage is likely to make changes Session_ ID,
such as destroying an old session_id, creating a new session_id. Half used in custom session operations, role conversions,
For example, Drupal.drupal's anonymous user has a session, and when it logs in, it needs to swap with the new session_id

        if (Isset ($_cookie[session_name ())) {
           Setcookie (Session_name (), ', Time ()-42000, '/');//Old session cookie expires
        session_regenerate_id ();// This step generates a new session_id
      //session_id () to return a new value

3. Write Session operation
At the end of the script will perform session write operation, the value of $_session to write to the session_id named file, may already exist,
You may need to create a new file.
* 4. Destroy session
The cookie that is sent by the session is usually an instant cookie that is stored in memory and expires when the browser is closed, and if it is forced to expire manually,
For example, to log out instead of closing the browser, you need to destroy the session in the code, there are many ways
o 1. Setcookie (Session_name (), session_id (), Time ()-8000000,..); /Log out before execution
o 2. Usset ($_session);//This will delete all $_session data, after the refresh, there is a cookie passed, but no data.
o 3. Session_destroy ();//This function is more thorough, delete $_session delete SESSION file, and session_id

When the browser is not closed, refresh again, 2 and 3 will have a cookie to pass, but no data found

2.session.save_handler = user

User-defined session processing mechanism, more intuitive
* Session_set_save_handler (' open ', ' close ', ' read ', ' write ', ' destroy ', ' GC ');
1.session_start (),
Execute open ($save _path, $session _name) Opening session action handle
$save _path in the case of Session.save_handler = files, it is Session.save_path,
However, if the user is self-determined, this two parameters are not used, directly return True

Reads the data from the read ($id).//This parameter is automatically passed session_id (), which can be manipulated by this value.
* 2. End of script execution
Execute write ($id, $sess _data)//two parameters, very simple
* 3. If the user needs Session_destroy ()
Execute the destroy first. In the 2nd step of execution

A practical example:

The code is as follows

Called when session is initialized
function open ($save _path, $session _name)
Global $sess _save_path;
$sess _save_path = $save _path;
return (true);

Called when it is closed
function Close ()
return (true);

      function Read ($id)
         Global $sess _save_path;
        $sess _file = "$sess _save_path/sess_$id";
        Return (String) @file_get_contents ($sess _file);
     //script execution is completed before execution, write
      function write ($id, $sess _ Data)
        echo "SDFSF";
         global $sess _save_path;

$sess _file = "$sess _save_path/sess_$id";
if ($fp = @fopen ($sess _file, "W")) {
$return = fwrite ($fp, $sess _data);
Fclose ($FP);
return $return;
} else {
return (false);


function Destroy ($ID)
Global $sess _save_path;

$sess _file = "$sess _save_path/sess_$id";
Return (@unlink ($sess _file));

Global $sess _save_path;

foreach (Glob ("$sess _save_path/sess_*") as $filename) {
if (Filemtime ($filename) + $maxlifetime < time ()) {
@unlink ($filename);
return true;


1. session  and COOKIES are two different things. On the PHP sever side, you can use the global function $_cookie[' xxx ' to access the value of cookies, set the cookie content by Setcookie, you can set your own named cookie name and value. The session can be known to be stored on the sever side of the file, it can be understood that the server has a session file (the unique session ID), and then send to the client session ID and value. The client saves the session mainly through the cookie to save (there are two other ways, less use), and then the client so every request is a cookie content, and the session ID name is a certain rule, in the server so if you want to use Seesion, Then it determines whether there is a session in the cookie, if there is to get over (session ID and its value), and then based on the server session comparison, if the same is a legitimate sesion, and then this client session can be used, Then continue the session process.

2. The expiration time of the session is set in PHP.ini, the default session.gc_maxlifetime = 1440 , but the session will not necessarily be recycled after it expires (unless actively unset or distory), Session recycling is a chance, the default is 1/1000, is in PHP every visit. I was thinking, if a site is very small, according to the design of a session is to expire, but if it has not been a long time to promote the recovery mechanism, then the session file is always there? If this is the case, then PHP to determine whether the session expires is not much use (time has been extended), I was still wondering, then whether this judgment is outdated by other aspects to set it? For example, in the Seesion file to set an expiration time, then the end gets to this session and value, but based on the current time and the expiration time comparison, the same can judge the session past. But I looked online a lot, but did not send a line session can set the expiration time. Session recycling is also based on the last modification time of the file, the current time, the expiration time of the three time to determine whether it expires. Although I haven't found out what the detailed mechanism is, I found a session_set_cookie_params this can set the cookie expiration time. If I understand it as above, then you can set the cookie time to achieve the session expiration effect.

The session mechanism in PHP

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.