Understand the principle of cookie and session mechanism correctly

Source: Internet
Author: User
Tags 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. This sessionid will be returned to the client in this response to save.

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

This technology is now being rewritten before being passed on to the client, and it is used by the very old IPlanet6 (the predecessor of the SunOne Application server) that the author has approached. 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, When you close the browser, the SessionID disappears and you cannot find the original session when you connect to the server again. 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

}

Else

{

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");

}

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 is a cookie, as we all know, HTTP is a stateless protocol, each 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 the php.ini, but some systems are session.gc_probability = 0, which means that the probability is 0, instead of 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 a $_cookie[session_name ()];session_name () to return the COOKIE key value that holds the session_id, which can be found from php.ini session.name = PHPSESSID//Default value PHPSESSID

3. If it does not exist, it will generate a session_id, and then pass the generated session_id as the value of the cookie to the client. The equivalent of performing the following cookie operation, note that this step performed the Setcookie () operation, Cookies are sent in header headers, which cannot be output before, and 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 designated folder to find the name ' Sess_ '. session_id () file. The contents of the read file are deserialized and then placed in the $_session

2. Assigning values to $_session

For example, add a new value $_session[' test ' = ' blah '; Then this $_session will only be maintained in memory, when the script execution is finished,

Write the value of the $_session to the folder specified in session_id, and then close the related resource. This stage is likely to perform changes to the session_id, such as destroying an old session_id, creating a new Session_ ID. Half used in the custom session operation, the role of the conversion, such as Drupal.drupal Anonymous user has a session, when it login need to swap with the new session_id

if (Isset ($_cookie[session_name ())) {

Setcookie (Session_name (), ", Time ()-42000, '/');//old session cookie expired

}

SESSION_REGENERATE_ID ();//This step will generate a new session_id

SESSION_ID () returns a new value

3. Write Session operation

A session write is performed at the end of the script, the value of $_session is written to the session_id named file, it may already exist, and a new file may need to be created.

4. Destroy session

The cookie that is sent to the session is usually an instant cookie, stored in memory, when the browser is closed, expires, if the need to artificially force expiration, such as log out, rather than close 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 handle $save_path in Session.save_handler = In the case of files it is Session.save_path, but if the user is self-determined, this two parameter is not used, directly returns TRUE, executes read ($ID) from which the data reads.//This parameter is automatically passed session_id (), 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 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);

}

Write operation is performed before script execution finishes

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;

}

Understand the principle of cookie and session mechanism correctly

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.