PHP Cookie and Session tutorial, cookiesession

Source: Internet
Author: User
Tags website server server memory

PHP Cookie and Session tutorial, cookiesession
■ Cookie 1. Why do I need cookies? First, we need to know that http is a stateless protocol. ● What is a stateless protocol? The status of the Protocol indicates the ability to "remember" The transfer information during the next transmission. Http does not maintain the information transmitted by this connection for the next connection, in order to ensure the server memory. For example, if the customer closes the browser after obtaining a webpage, then starts the browser again and then logs on to the website, but the server does not know that the customer closes the browser once. Therefore, http is a stateless protocol. While DNS is a stateful protocol. It is because http is a stateless protocol. If multiple pages in a website need to share the same information, how can this problem be achieved? A: Through cookies and sessions, we can share the same information across multiple pages.★The most typical application of Cookie and Session is to determine whether a registered user has logged on to the website. Another important application scenario is "Shopping Cart. Users may select different items on different pages of the same website within a period of time. These information will be placed in the Session "Shopping Cart object" to extract information during the final payment. Ii. Cookie Transfer Process: ① when the client first accesses a website, the server program will send you a Cookie along with the response of the webpage. ② When the client (browser) obtains and saves the Cookie of the website, if it accesses the website again (including redirecting to another page of the same website through links or other means) in this case, the browser will check whether the Cookie file related to the domain name is saved on the machine (the browser will save the Cookie based on different domain names or IP addresses ). ③ If the Cookie is found, the browser sends the data in the Cookie together with the previously entered URL to the website server. ④ After the server receives the Cookie data, it will retrieve the information you leave on the website in its database and add the new content to the database and Cookie. ⑤ If no Cookie related to the domain name is found or your Cookie information does not match the information in the database, it indicates that you are visiting the website for the first time or that your Cookie has been lost. 3. Cookie implementation principle: cookies are transmitted using the http header information in the webpage code. Each web page request of the browser can be transmitted along with the Cookie. For example, open or refresh a web page in a browser. The server adds the Cookie to the http header of the webpage. When the webpage data is sent back to your browser, the browser will choose whether to save the data based on the Cookie settings on your computer. Even if the client sets the Cookie to be saved, the Cookie will affect the time it is saved on the client according to the requirements of the server. Cookie has an Expires (Validity Period) attribute, which determines the Cookie retention time. The server can change the Cookie retention time by setting the value of the Expires field. If this attribute is not set, the Cookie will only be valid during the running of the browser. After the browser is closed, these cookies will automatically disappear. This is the case for most websites. In addition, the Path (valid Path) attribute of the Cookie is used to specify the directory to which the Cookie will be sent to the server. If this attribute is not set, the directory in which the Cookie is set is valid only in this directory and Its subdirectories. Iv. Cookie restrictions: the number of cookies under each domain name cannot be infinite (varies according to the requirements of different browsers). Generally ~ 40. Each Cookie cannot be infinitely large (varies according to different browser Rules). Generally, it cannot exceed 4 kb. V. $ _ COOKIE: predefined variable (Super global variable) $ _ COOKIE indicates the Cookie information transmitted from the browser. 6. PHP system function setcookie (): in PHP, we can set the Cookie through the built-in function setcookie (). The usage is as follows: setcookie ('name ', 'content', validity period, 'valid path', 'valid domain name', whether to pass through https only, and whether to pass through http only) parameter resolution: the first parameter represents the Cookie name. The second parameter indicates the content of the Cookie. The third parameter indicates the Cookie validity period, which must be in the form of a timestamp. The fourth parameter indicates the valid path of the Cookie. The fifth parameter represents the valid Domain Name of the Cookie, which is used when cross-domain names are required. The sixth parameter indicates whether to transmit data only over https. The seventh parameter indicates whether to transmit data only over http.★Note: ① The third parameter indicates the Cookie validity period. If this parameter is not set, the Cookie is valid only when the browser is running. When the browser is closed, the Cookie disappears automatically (Session-level Cookie ). For example, set the Cookie validity period to 30 seconds. The Code is as follows: setcookie ('name', 'content', time () + 30); // use the system function time () obtain the current timestamp. The Cookie still exists even if the browser is closed within 30 seconds (within the validity period. ② The fourth parameter represents the valid path of the Cookie. If this parameter is not set, the directory in which the Cookie is set is valid only in this directory and Its subdirectories. For example, set the valid Cookie Path to the root directory (that is, the whole site). The Code is as follows: setcookie ('name', 'content', time () + 30 ,'/'); if the valid path is set to the root directory, the Cookie is valid in any directory of the entire site. ③ When using the system function setcookie (), no output statement can be prepared before setcookie. When the server executes setcookie (), the server returns a Set-Cookie header to the client (browser. When the client (browser) receives the header information, it sets a Cookie before processing the subject information. (★Summary: no subject information can be output before header information is set .) ④ Setcookie () is set to "issued Cookie" (that is, the Cookie sent by the server to the browser ); the $ _ COOKIE stores the "recycled Cookie" (that is, the Cookie information sent by the browser to the server ). The "issued Cookie" is different from the "recycled Cookie", so modifying $ _ COOKIE cannot change the Cookie information of the client. You can only use setcookie () to modify the Cookie to be sent to the client. Otherwise, the content in the current $ _ Cookie cannot be changed through setcookie. 7. How to destroy a Cookie: for example, if the validity period is zero, the Cookie has expired. Setcookie ('username', '', 0); setcookie ('username','', 0, '/'); 8. Cookie security issues (Cookie defects ): because the Cookie is stored on the client (browser), it is easy for users to modify and forge. Therefore, Cookie information is not reliable and we need Session. Cookie applications: generally used to record browsing history, counters, and other tracking information. Do not store important information such as accounts and amounts. ■ Session 1. Why do I need a Session? Let's take an example in our daily life: a bank card is generally obtained when we open an account and deposit at a bank. If our account name and deposit are directly written on the bank card, and the bank will only judge our identity and deposit based on the account name and deposit value on the bank card. Do you think this is feasible? The answer is obvious. Of course it is not feasible: we have the bank card in our hands. We can change the information on the bank card. This is not safe or reliable for banks or customers. Cookie is like the bank card mentioned above. The Cookie is stored on the client, and you can modify its content at will. So how can we solve the problem of insufficient Cookie security? We will continue to return to the bank card based on examples in our daily life. Let's think about how bank cards are in real life. The bank card we use does not contain our information. It only prints a string of numbers (of course, there are magnetic stripe and chips, but they all have the same nature ). Our information is stored in the bank. Every time we go to the bank for business, the bank will find our information in the bank based on our card number and work accordingly. The server is like a bank. Our information is stored in the Session and stored on the server. A Cookie is like a bank card. It saves a session_id and is like a bank card number ". When we access the server again, the client (browser) will find the Cookie and pass it to the server. The server will find the corresponding Session file based on the session_id in the Cookie, then, process the request based on the information in the Session file. Through Session, you can make up for Cookie deficiencies and solve security problems. Ii. Session workflow: ① when a user visits a page of the website for the first time, the server generates a Session to save the user's related information. The Session file is saved in the specified directory on the server. Each Session has a session_id associated with the Session file name. For example, if session_id is bumv972oav16dr1qv96a1omd92, the Session file name is sess_bumv972oav16dr1qv96a1omd92. ② The Server puts session_id in the Cookie, and sends the response of the webpage to the client (browser ). ③ When the user accesses the server next time, the client (browser) will find the Cookie and pass it to the server. The server will find the corresponding Session file based on the session_id in the Cookie, then, the user's request is processed based on the content in the Session file. 3. Set the Session storage path: Find the following content in php. ini and set session. save_path = "D :/...... "IV. Common Session functions: ● session_start () ---- function: Create a new Session or reuse an existing Session. That is to say, if the client (browser) does not submit session_id, this function will create a session_id for you (that is, to respond to the client with a Cookie whose content is session_id) and create a Session file associated with it. If the client (browser) submits session_id, this function searches for the corresponding Session file in the specified directory based on session_id. If the corresponding Session file is not found, a new Session file is created based on session_id.★Note: ① The session_start () function must be called before the Session is read, edited, and destroyed; ② the valid path for saving and passing the Cookie "session_id" is the root directory by default. You can find the following content in php. ini and set it: session. cookie_path =/● session_id ([string]) ---- function: Get or set the current session_id. ● Session_unset () ---- function: clears the Session content. ● Session_destroy () ---- function: destroy the Session. V. $ _ SESSION: You can directly read and edit sessions through predefined variables (Super global variables) $ _ SESSION. For example, session_start (); // you must call it before reading, editing, and destroying a Session. $ _ SESSION ['user'] = 'zhang san ';★Note: Unlike cookies, operations on $ _ cookies directly do not affect cookies because they are stored on the client (browser ). Vi. Method of destroying a Session: the effect of destroying a Session includes the following three methods: // ① destroy the Cookie that saves "session_id": // note: the valid path for saving the Cookie "session_id" is the root directory by default. Setcookie ('phpsessid ', '', 0,'/'); // ② clear the Session: $ _ SESSION = array (); // or use the system function session_unset (); // ③ destroy Session: session_destroy (); 7. Session validity period: the Session validity period is controlled by two aspects: ① The validity period of the Cookie that saves "session_id"; ② the server cleans up the Session file. By default, when the browser Session is closed, it becomes invalid! It does not disappear. By default, the Cookie that saves "session_id" disappears automatically as the browser closes. However, the Session file on the server still exists.★Set the Cookie validity period for saving "session_id": in php. find the following content in ini and set it: session. cookie_lifetime = 0 Note: 0 indicates the default situation, that is, it is valid during the browser running.★Session file cleanup mechanism: when the server is requested, it determines whether to clear expired Session files by a certain probability. How to determine whether the Session file has expired: Determine whether the stay time of the Session file has exceeded the specified number of seconds based on the last modification time of the Session file (default: 1440 seconds ). Why should we determine whether to clear expired Session files with a certain probability? This is because the Session file will be cleared in each request, which will bring great overhead to the system. Due to the above reasons, an issue occurs: expired Session files cannot be cleared in time. Solution: store the Session file in memcached and set a validity period for memcached. 8. Main differences and connections between sessions and cookies: ① sessions are stored on the server, while cookies are stored on the client (browser ). ② Cookies cannot store arrays, objects, and resource types. Session can be of other types except resource types. (★This also means that $ _ SESSION may be a two-dimensional or multi-dimensional array .) ③ The Session is created through session_start () and can be read and edited directly through $ _ SESSION. The Cookie can be read through $ _ COOKIE, but cannot be edited through $ _ COOKIE. You can use setcookie () to create, edit, and destroy cookies. Contact: The Session operation must be assisted by the Cookie. The Cookie must be used to transmit the "session_id" between the client (browser) and the server.

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.