Cookie and session

Source: Internet
Author: User
Tags php session unique id

1. What is Cookie?

Cookie is a mechanism for storing data in a remote browser and tracking and identifying users.

2. COOKIE Mechanism

Web applications transmit data over HTTP. HTTP is a stateless protocol. Once the data exchange is complete, the connection between the client and the server is closed, and a new connection is required for data exchange again. This means that the server cannot trace sessions from the connection. The cookie mechanism can make up for the stateless HTTP protocol.

Cookie is actually a short text message. The client requests the server. If the server needs to record the user status, it uses response to issue a cookie to the client browser (the server sends an HTTP set-Cookie header Through response ). The client browser creates a cookie file on the client disk and saves the cookie. When the browser requests the website again, the browser submits the requested URL together with the cookie to the server. The server checks the cookie to identify the user status. The server can also modify the cookie content as needed.

If no expiration time is set, it indicates that the life cycle of the cookie is the browser session period. When the browser window is closed, the cookie disappears. This cookie is called a session cookie. Session cookies are generally stored in the memory instead of on the hard disk. Of course, this behavior is not standardized. If the expiration time is set, the browser will save the cookie to the hard disk, and then open the browser again. These cookies are still valid until the preset expiration time is exceeded.

 

3. How to use cookies in PHP

Create cookie

Bool setcookie (string $ name [, string $ value [, int $ expire = 0 [, string $ path [, string $ domain [, bool $ secure = false [, bool $ HTTPOnly = false])

All parameters except $ name are optional. The string type parameter can be set to "" to skip. $ expire is int type and can be set to 0 to skip.

Example

 

<? PHP

$ Value = 'something from somewhere ';

Setcookie ("testcookie", $ value );

Setcookie ("testcookie", $ value, time () + 3600);/* expire in 1 hour */

Setcookie ("testcookie", $ value, time () + 3600 ,"/~ Rasmus/"," example.com ", 1 );

?>

Use header () to set the cookie;

Header ("Set-COOKIE: name = $ value [; Path = $ path [; domain = xxx.com [;...]");

Get cookie

The $ _ cookie variable of PHP is used to retrieve the cookie value.

<? PHP

Echo $ _ cookie ["testcookie"];

Print_r ($ _ cookie );

?>

 

Delete cookie

Delete a cookie by setting the expiration date to the past date/time

<? PHP

Setcookie ("testcookie", "", time ()-3600 );

?>

 

4. What is session?

A session stores user information on the server to maintain an uninterrupted request response sequence between the client and the server.

5. session mechanism

Create a unique ID (UID) for each visitor and store the variables based on the UID. The UID is stored in the cookie or transmitted through the URL.

When starting a session, PHP will try to find the session ID (usually through session cookie) from the request. If the request does not contain the session ID information, PHP will create a new session. After the session starts, PHP sets the data in the session to the $ _ session variable. When PHP stops, it automatically reads the content in $ _ session, serializes it, and sends itSession save ManagerTo save.

When you access the page again, the session ID is submitted to the server to access session data. 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 rewrite the URL to save the session value.

Some session configuration options:

Session. save_path defines the parameters passed to the storage processor. If the default files file processor is selected, this value is the path of the file to be created. The default value is/tmp.

Session. save_handler defines the name of the processor used to store and obtain the data associated with the session. The default value is files.

Session. Name specifies the session name to use as the cookie name. It can only consist of letters and numbers. The default value is PHPSESSID.

Session. use_cookies specify whether to use cookies on the client to store session IDs. The default value is 1 (Enabled ).

Session. cookie_lifetime specifies the lifecycle of the cookie sent to the browser in seconds. If the value is 0, it means "until the browser is closed ". The default value is 0.

6. How to Use session in PHP

Start PHP session

<? PHP session_start ();?>

 

<HTML>

<Body>

 

</Body>

</Html>

The above code registers a user's session with the server so that you can start to save the user information and assign a UID to the user session.

Store session Variables

The correct method for storing and retrieving session variables is to use the PHP $ _ session variable:

<? PHP

Session_start ();

 

If (isset ($ _ session ['view'])

$ _ Session ['view'] = $ _ session ['view'] + 1;

 

Else

$ _ Session ['view'] = 1;

Echo "views =". $ _ session ['view'];

?>

End session

If you want to delete some session data, you can use the unset () or session_destroy () function.

The unset () function is used to release the specified session variable. The session_destroy () function completely ends the session.

<? PHP

Unset ($ _ session ['view']);

Session_destroy ();

?>

 

7. Differences between cookies and sessions

The cookie mechanism adopts the client-side persistence scheme, while the session mechanism adopts the server-side persistence scheme.

The cookie variable value is stored on the client. The session variable value is stored on the server and distinguished by sessionid. Session is based on cookie or URL rewriting and is implemented by Cookie by default, the system will create an output cookie named JSESSIONID, called session cookie, to distinguish persistentcookies. Note that sessioncookie is stored in the browser memory and is not written to the hard disk. Session Cookie for a session, the session end sessioncookie disappears, and the persistentcookie only exists in a piece of text (usually encrypted) on the client's hard disk ), in addition, Cookie spoofing and cross-site scripting attacks against cookies are not as secure as session cookies.

A session is stored on the server. Each user generates a session. If a large number of concurrent users are accessed, a large number of sessions are generated, consuming a large amount of memory. The cookie is stored on the client and does not occupy server resources.

Cookie and session

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.