Explain the difference between cookie and session in PHP and cookie and Session usage Summary _php example

Source: Internet
Author: User
Tags httpcontext session id sessions

Specifically, cookies are stored in the "client" and the session is stored on the "server"

Cookies are implemented by extending the HTTP protocol

Cookies mainly include: name, value, expiration time, path and domain;

If the cookie is not set to a lifecycle, it is closed with a browser shutdown, which is typically stored in memory rather than on the hard disk. If you set a lifecycle, instead of disappearing with the browser shutdown, the cookies are still valid until you exceed the set expiration time.

Session to save information in a form similar to a hash table,

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 the session ID), if already included, the server retrieves the session by the session ID, if it has previously been created for this client (not retrieved, creates a new one), and if the client request does not contain the sessions ID, A session is created for this client and a value that generates a session Id,session ID associated with this session should be a string that neither repeats nor is easily found to mimic, this session The ID will be returned to the client for saving in this response. This session ID can be saved in a cookie, so that the browser can automatically send the identity to the server according to the rules during the interaction. Generally this cookie's name is similar to Seeesionid. However, cookies can be artificially prohibited, and there must be other mechanisms to pass the session ID back to the server when the cookie is blocked.

Disadvantages

1, the cookie data stored in the customer's browser, session data on the server.

2, cookies are not very safe, others can analyze stored in the local cookies and cookie spoofing
Consider that security should use session.

3, session will be stored in a certain period of time on the server. When the visit increases, it will take up the performance of your server

Consider the use of cookies for mitigating server performance.

4, a single cookie can not save more than 4K of data, many browsers limit a site to save up to 20 cookies.

5, so personal recommendations:

Storing important information such as login information as session

Additional information, if required, can be placed in a cookie

Summary of Session and cookie usage:

Both session and cookie are built-in objects in the ASP.net, so what's the difference between them, here is not to say, now say something more practical:

We know that the site has a background management system, which has login and exit two functions, in the login when we tend to save the user's information to the session or cookies, so that later use, then in the log when we should pay attention to what?

1, put some sensitive things into the session, less sensitive things can exist in the session or cookies, such as user name is not very sensitive, but in some browsers do not support the use of cookies, so we will save it to the session, But the session sometimes in the server is easy to lose, so we can use the cookie together, that is, when the session is lost, if the cookie is still within the lifetime of our set, we can again from the cookie out of the value into the session, So we'd better keep the username and so on with the session and cookies, or in the config file.

Copy Code code as follows:

<sessionstate timeout= "2" mode= "StateServer"/>



To solve the problem of session loss can also be

2, we hope that the background management in the case of how long there is no operation, let session failure, re-login, you can use session.timeout=5, in minutes, means that 5 minutes no other operations, will fail, or in the configuration file configuration < sessionstate timeout= "5" mode= "InProc"/> can also

3, the validity of the cookie set

Httpcookie.expires = DateTime.Now.AddMinutes (2);

Cookies are valid for 2 minutes

4, the page to determine whether there is permission to access the Web page, you can judge as follows:

if (request.cookies["HttpCookie"]!= null)
{
session["admin"] = request.cookies["HttpCookie"]. values["Admin"]. ToString ();
}
if (session["admin"] = = null)
{this
. Clientscript.registerstartupscript (this. GetType (), "", "<script>alert (' please login again '); location.href= ' logins.aspx ' </script>");

Here's how to do it when you're quitting.

1, the exit time session and the value of the cookie must be emptied, now to briefly talk about the difference between the several methods of the session:

Session.clear (): Indicates that the key value for all sessions in the session is emptied, but still exists with the same equals Session.removeall ()

session["Admin"]=null: The value of the key will be set empty, and released, and session["admin"]= "" is not the same, it emptied, but the session does not release, the same equals session. Remove ("name");

Session.Abandon () is to delete the current session object, the next time is a new session.

The main difference is that when Session.Abandon is used, the Session_End method (InProc mode) is invoked. The Session_Start method is fired when the next request arrives. And Session.clear just clears all the data in the session and does not abort the

Session, and therefore does not call those methods, the Abandon method is used to actively end the conversation, and if the method is not invoked, the current session is automatically terminated when the session times out.

2, below to see how to clear cookies

A, Tpcookie cookie = System.Web.HttpContext.Current.Request.Cookies.Get ("Tuser");

Cookie. Expires = DateTime.Now.AddDays (-1);
SYSTEM.WEB.HTTPCONTEXT.CURRENT.RESPONSE.COOKIES.ADD (cookie);

B, Tpcookie HttpCookie = request.cookies["HttpCookie"];

Httpcookie.expires = DateTime.Now.AddDays (-1);
RESPONSE.COOKIES.ADD (HttpCookie);

AB Two ways can be

3, so the session to clear the current value can be that session["admin"]=null on it, cookies in accordance with the above method to clear the

Suggestions and comments:

1, in the exit when we can create a logout page to write time, so better

2, no matter what the operation of the time, can use if to determine whether the case is empty to judge as far as possible, to prevent the occurrence of null pointer anomalies

The above is a small set to introduce the details of PHP cookie and session of the difference and cookies and session usage summary of the relevant knowledge, hope to help everyone, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.