Cookies and session application learning notes in php

Source: Internet
Author: User
Tags set cookie
In php, the difference between cookie and session is that cookie data is stored on the client, and session data is stored on the server. Naturally, there will be some differences in the usage method, but later

In php, the difference between cookie and session is that cookie data is stored on the client, and session data is stored on the server. Naturally, there will be some detailed differences in usage, however, it is much safer than the former.

1. cookie & session introduction and differences

Cookie data is stored on the client, and session data is stored on the server.

Simply put, when you log on to a website, if the web server uses a session, all the data is stored on the server, each time the client requests the server, it sends the sessionid of the current session. the server determines whether the user is logged on or has certain permissions based on the current sessionid. Because the data is stored on the server, you cannot forge it. However, if you can obtain the sessionid of a logon user, using a special browser to forge the user's request is successful. Sessionid is randomly allocated when the server and client are connected. Generally, there will be no duplicates. However, if there are a large number of concurrent requests, there is no possibility of repetition. I have met it once. Log on to a website and start to display your own information. when a period of time has elapsed, a refresh will display others' information.

If the browser uses cookies, all the data is stored in the browser. for example, after you log on, the server sets the cookie username, when you request the server again, the browser will send the username to the server. these variables are marked with special characters. The server is interpreted as a cookie variable. So as long as the browser is not closed, the cookie variable will always be valid, so it can ensure that the line is not dropped for a long time. If you can intercept a user's cookie variable and then forge a data packet to send it, the server still thinks that you are legal. Therefore, cookie attacks are more likely. If the validity period is set, the cookie is saved on the client's hard disk. when you access the website again, the browser checks whether there is any cookie, read the cookie and send it to the server. If you save a Forum cookie on your machine, it will be valid for one year. if someone intrude into your machine, copy your cookie and put it under the Directory of his browser, then he logs on to the website as you. Therefore, cookies can be forged. Of course, the idea is required to copy the cookie file directly to the cookie Directory. the browser does not recognize it and has an index. the dat file stores the creation time of the cookie file and whether the file has been modified. Therefore, you must first have the cookie file for the website and cheat the browser from the guaranteed time, I once tried it on the school's vbb Forum and copied others' cookies to log on. I posted a post in the name of someone else. there is no problem at all.

Session is a server-side storage space maintained by the application server. when you connect to the server, the server generates a unique SessionID, use this SessionID as the identifier to access the Session bucket on the server. SessionID is saved to the client and saved using cookies. when a user submits a page, the SessionID is submitted to the server to access Session data. This process requires no developer intervention. Therefore, once the Cookie is disabled on the client, the Session will also become invalid.

The server can also pass the SessionID value through URL rewriting, so it is not completely dependent on cookies. If the client Cookie is disabled, the server can automatically save the Session value by rewriting the URL, and this process is transparent to the programmer.

You can try to use the request even if no Cookie is written. getCookies (); the length of the retrieved Cookie array is also 1, and the Cookie name is JSESSIONID. There is also a long binary string, which is the value of SessionID.

2. cookie configuration and application

Basic syntax: setcookie ("cookie", "cookievalue", time () + 3600, "/forum", ".xxx.com", 1 );

Effective time of the name value, whether to use https to save the domain in milliseconds

Access and process cookies

The basic access syntax is as follows:

  1. Echo $ mycookie;
  2. Echo $ cookiearray ['0'];
  3. Echo $ _ COOKIE ['mycooker']; (recommended)
  4. Echo $ HTTP_COOKIE_VARS ['mycooker'];

Delete cookie

Delete the basic syntax. the code is as follows:

  1. Setcookie ("cookie", ""); (overwrite the original value with an empty cookie)
  2. Setcookie ("cookie", "value", time ()-1/time (); (time destruction)

The instance code is as follows:

  1. If ($ _ POST ['user'] & $ _ POST ['password']) {
  2. Setcookie ("us", $ _ POST ['user']);
  3. Setcookie ("pwd", $ _ POST ['password']);
  4. Echo "User:". $ _ COOKIE ['us']." "." Password: ". $ _ COOKIE ['pwd'];
  5. }
  6. ?>
  7.  

Note: You must complete the cookie operation before output; otherwise, error occurs.

1. session configuration and application

The code is as follows:

  1. Session_start (); // initialization, which must be placed in the file header.
  2. $ _ SESSION ['name'] = value; // Configure the session.
  3. Echo $ _ SESSION ['name']; // use session.
  4. Isset ($ _ SESSION ['name']); // judge.
  5. Unset ($ _ SESSION ['name']); // delete.
  6. Session_destroy (); // destroy all sessions.

Here are some examples to illustrate the differences between session and cookie.

<一> : Session

Start session: session_start ();

Summary: This function needs to be placed at the front end of the file. There should be no output at the front end. it is best to write it at the top (there should be no leading space ).

Set session: $ _ SESSION ['name'] = 'value ';

Summary: Directly set the value using the $ _ SESSION [] method. The "[]" part is the name of the session, and "=" is followed by the value.

Read session: echo $ _ SESSION ['name'];

Summary: Enable session (use session_start () before setting or reading a session ()).

Destroy session:

1. close the browser and destroy it automatically.

2. directly give $ _ SESSION [] = ''; clear.

<二> : Cookie

Set cookie:

Bool setcookie (string name [, string value [, int expire [, string path [, string domain [, bool secure [, bool httponly])

Name: cookie variable name

Value: The value of the cookie variable.

Expire: the end time of the validity period,

Path: valid directory,

Domain: valid domain name, unique in top-level domain

Secure: if the value is 1, the cookie can only be valid for https connections. if the default value is 0, both http and https can be used.

Example: setcookie ('username', 'hello', time () + 3600 );

Setcookie ("username", 'hello', time () + 3600 ,"/~ Rasmus/"," .paea.cn ", 1 );

Summary: No output data operation can be performed before setcookie; otherwise, an error similar to session_start () will occur ().

Read cookie:

Echo $ _ COOKIE ['username']. '| ';

Echo $ HTTP_COOKIE_VARS ["username"];

Summary: Two output modes.

Destroy cookie: Set a past time to cancel the cookie

Setcookie ('username', 'hello', time ()-3600 );

Summary: No output data operation can be performed before setcookie; otherwise, an error similar to session_start () will occur ().

To sum up

Purpose: Both session and cookie are used to temporarily record user data.

Differences:

1. the SESSION is stored on the server. users cannot modify the SESSION. it is safer. cookies are stored on the client. Users can modify the SESSION, which is not safe.

2. the Session will be stored on the server for a certain period of time and will occupy server resources. Cookies are stored in the Temp directory of your windows system.

3. the limit for a single cookie on the client is 4 k.

4. use $ _ session [] for SESSION Traversal and $ _ cookie [] for COOKIE traversal

5. the session cannot be used after the cookie is disabled.

6. when the session is used, session_start () must be added and no output is available.

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.