Understand the principle of cookie and session mechanism correctly

Source: Internet
Author: User
Tags garbage collection hash http request session id sessions setcookie cron script drupal

The difference and connection between cookie and session mechanism

Specifically, the cookie mechanism uses a scheme that maintains state on the client. It is the memory mechanism of the session state at the client side, and he needs the user to open the cookie support for the clients. The role of cookies is to solve the HTTP protocol stateless defects made efforts.

The session mechanism uses a solution that maintains state between the client and the server. At the same time, we also see that the session mechanism may need to use the cookie mechanism to save the identity because the server-side retention scheme also needs to be stored in the client. and session provides a convenient way to manage global variables

The session is for each user, the value of the variable is saved on the server, with a sessionid to distinguish which user sessions variable, which is returned to the server through the user's browser, when the client disables cookies, This value may also be set to be returned to the server by get.

In terms of security: When you visit a site using session and create a cookie on your own machine, it is recommended that the session mechanism on the server side be safer. Because it does not arbitrarily read the information that the customer stores.

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

From a network 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 network client and server to maintain the relationship between requests. The period during which this relationship is maintained is called a session.

Cookies are small pieces of text stored on the local machine by the server and 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 at the client terminal, the browser resolves the cookies and saves them as a local file, which automatically binds any request of the same server to the cookies

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

Understanding the session mechanism

The session mechanism is a server-side mechanism in which the server uses a structure similar to a hash table (or perhaps a hash table) to hold the 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 you already have a sessionid that has previously created a session for this client, the server retrieves the session in accordance with SessionID (a new one may be created if it is not retrieved), if the client request does not contain SessionID, A session is created for this client and a value that generates a Sessionid,sessionid associated with this session should be a string that neither repeats nor is easily found to mimic. This sessionid will be returned to the client for saving in this response.

The way to save this sessionid is to use cookies so that the browser can automatically play the logo to the server in the interactive process. Generally this cookie's name is similar to Seeesionid, and. For example, WebLogic for Web application-generated cookie,jsessionid=byok3vjfd75apnrf7c2hmdnv6qzcebzwowibyenlerjq99zwpbng!- 145788764, its name is Jsessionid.

Since cookies can be artificially banned, there must be other mechanisms to pass the SessionID back to the server when the cookie is blocked. A technique that is often used is called URL rewriting, which is to attach SessionID directly behind the URL path, and there are two additional ways, one being the additional information as a URL path, which is represented by 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 users is no difference, but the server in the resolution of the different ways to deal with, the first way is also conducive to sessionid information and normal program parameters to distinguish.

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

Another technique is called a form-hiding field. The server automatically modifies the form and adds a hidden field so that the SessionID can be passed back to the server when the form is submitted. Like the following form

will be overwritten before being passed to the client

This technique is now less applied, and the old IPlanet6 (formerly known as the SunOne application server) that I have contacted have used this technique.

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

When talking about the session mechanism, it is often heard that "as long as the browser is closed, the session disappears." In fact, you can imagine the membership card example, unless customers take the initiative to put a PIN card, otherwise the store will not easily delete the customer's information. For the session is also the same, unless the program to notify the server to delete a sessions, otherwise the server will remain, the program is generally in the user to do logoff when a command to delete session. However, the browser never proactively notifies the server that it is shutting down before shutting down, so the server will never have a chance to know that the browser has been turned off, and this illusion is that most session cookies are used to save SessionID. When the browser is closed, the SessionID disappears, and when you connect to the server again, you can't find the original session. If the server set the cookie is saved to the hard disk, or use some means to overwrite the browser issued the HTTP request header, the original SessionID sent to the server, then open the browser again can still find the original session.

Precisely because the browser does not cause the session to be deleted, forcing the server to set an expiration time for seesion, the server can assume that the client has stopped the activity when it is more than the expiration time from the time when the client last used sessions. Will remove the session to save storage space.

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

On the difference and connection between cookie and session by Jsessionid

On occasions like voting, we tend to ask everyone to vote for a fair number of reasons, and there are similar situations in web development where we usually use cookies, such as the following code:

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

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

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

Run Result:

Cookiename:JSESSIONIDcookievalue:KWJHUG6JJM65HS2K6 Why there are cookies, as we all know, HTTP is a stateless protocol, every time the client reads a Web page, the server opens a new session, And the server will not automatically maintain the client's contextual information, then how to achieve the online store in the shopping cart, the session is a mechanism to save contextual information, it is for each user, the value of the variables stored on the server side, through the sessionid to distinguish between different customers, The session is based on a cookie or URL rewrite and is implemented by default using cookies, and the system creates an output cookie called Jsessionid, called Sessioncookie, to distinguish Persistentcookies, Which is what we usually call cookies, notice that Sessioncookie is stored in browser memory, not on the hard drive, which is what we just saw jsessionid, we usually don't see Jsessionid, But when we disable the browser cookie, the Web server will pass SessionID in URL rewriting, and we can see strings like sessionid=kwjhug6jjm65hs2k6 in the address bar.

Understand the principle, we can easily distinguish between persistentcookies and sessioncookie differences, the Internet on the security of both the discussion also at a glance, Sessioncookie for a session, The session end Sessioncookie disappears, and Persistentcookie is just a piece of text (usually encrypted) that exists on the client's hard disk and can be spoofed by cookies and cross-site scripting attacks against cookies, Naturally, it's not as safe as 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 can not be achieved, At this point we can save the SessionID in the Persistentcookie, and then read it in a new window, we can get the previous window SessionID, In this way, through the combination of Sessioncookie and Persistentcookie, we implement the sessiontracking (session tracking) across Windows.

In some web development books, it is often simply the way to send sessions and cookies as two parallel HTTP messages, Sessioncookies is located on the server side, Persistentcookie is located on the client, But the session is based on cookies, 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 on 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 open garbage collection, because the session is stored in the file,
PHP's own garbage collection is invalid, the session of the recovery is to delete the file, the probability is based on the configuration of PHP.ini decision,
But some systems are session.gc_probability = 0, which means that the probability is 0, but the cron script is used to implement garbage collection.

session.gc_probability = 1
Session.gc_divisor = 1000
Session.gc_maxlifetime = 1440//expiration default 24 minutes
Probability is session.gc_probability/session.gc_divisor result 1/1000,
It is not recommended to set too small, because the session garbage collection, you need to check whether each file expires.
Session.save_path =//As if different systems default, one setting is "N;/path"
This is random tiered storage, this kind of word, garbage collection will not work, need to write their own script

2. The session will determine whether there is currently a $_cookie[session_name ()];session_name () that returns the COOKIE key value of the saved session_id.
This value can be found from php.ini

Session.name = PHPSESSID//default value PHPSESSID

3. If not present generates a session_id, then passes the generated session_id as the value of the cookie to the client.
Equivalent to performing the following cookie operation, note that this step performs the Setcookie () operation, the cookie is sent in the header header,
There is no output before this, PHP has another function session_regenerate_id () If you use this function, this can not 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 so session_id = $_cookie[session_name];
            then go to Session.save_path's designated folder to find the name ' Sess_ '. session_id () file.
            Read the contents of the file deserialized, and then put it into $_session
     * 2. Assign a value to the $_session
      For example add a new value $_session[' test ' = ' blah '; then this $_session will only be maintained in memory, When the script finishes,
writes the value of the $_session to the folder specified by session_id, and then closes the associated resource .      this phase is likely to perform a change session_ ID,
such as destroying an old session_id and generating a new session_id. Half used in custom session actions, role transitions,
For example, the anonymous user of Drupal.drupal 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 () returns a new value

3. Write Session operation
The session write operation is performed at the end of the script, and the $_session value is written to the session_id named file and may already exist.
You may need to create a new file.
* 4. Destroy session
The cookie that the session sends out usually belongs to the instant cookie, saves in the memory, when the browser closes, only then expires, if needs the artificial force expiration,
For example, to exit the login, rather than close the browser, you need to destroy the session in the code, there are many methods,
o 1. Setcookie (Session_name (), session_id (), Time ()-8000000, ...); /exit Pre-Logon execution
o 2. Usset ($_session)//This will delete all the $_session data, after refreshing, there is a cookie passed, but no data.
o 3. Session_destroy ()//This role 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 passed, 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 (),
Executes open ($save _path, $session _name) opens the session action handle
$save _path is session.save_path in the case of Session.save_handler = files,
But if the user is determined, this two parameters will not be used, directly return True

The execution of Read ($id) reads from the data.//This parameter is automatically passed is 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 the execution

A practical example:

The code is as follows Copy Code

Called when the 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, write operations
      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));
}

Function GC ($MAXLIFETIME)
{
Global $sess _save_path;

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

Then really understand the session work mechanism.

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: info-contact@alibabacloud.com 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.