Differences and relationships between cookies and Sessions-PHP Tutorial

Source: Internet
Author: User
Tags php session
Differences and relationships between cookies and sessions. I will share an article about the differences between cookies and Sessions. if you have any questions, please refer to this article. Cookies are often used to identify users. Cookie is an article on the differences between cookies and sessions shared by the server. if you need cookies, you can refer to it as a valuable article. Cookies are often used to identify users. Cookie is a small file that the server stays on the user's computer. When the same computer requests a page through a browser, it sends a cookie at the same time. With PHP, you can create and retrieve the cookie value. PHP uses the SetCookie function to set the Cookie. The SetCookie function defines a Cookie and attaches it to the end of the HTTP header. the prototype of the SetCookie function is as follows:
Int SetCookie (string name, string value, int expire, string path, string domain, int secure); parameter description: cookie name, cookie value, Expiration Time (int), valid path, limited domain name, only valid for https transmission
The code is as follows:
Note: the currently set Cookie does not take effect immediately, but will not be visible until the next page. this is because the Cookie is transmitted from the server to the client's browser on the configured page, and the Cookie can be retrieved from the client's machine and sent back to the server on the next page.
Example: common use: setcookie ('name', 'php Huaibei '); with Expiration Time:
Setcookie ('name', 'php Huaibei ', time () + 24*60*60); // 1dayCookie is path-oriented and is stored under the current file by default, if no path is set, cookies in different files are saved in different folders by default, and phphuaibei/201111/201111151945348209 .png"> 2. receive and process cookiesThe web communication protocol between the client and the server is http. PHP uses three methods to obtain user data over http: POST, GET, and Cookie. The default PHP transfer method is Cookie, which is also the best method. For example, if you set a Cookie named MyCookier, PHP will automatically analyze it from the HTTP header received by the WEB server and form a variable named $ myCookie, which is the same as a common variable, the value of this variable is the Cookie value. 3. delete a CookieThere are two ways to delete an existing Cookie:
  1. 1. if you call a SetCookie with only the name parameter, the Cookie named this name will be deleted from the relevant host. for example, setcookie ('name ','');
  2. Another method is to set the Cookie's expiration time to time () or time ()-1. then, the Cookie is deleted after the page is viewed (in fact, it is invalid ). For example, setcookie ('name', 'php Huaibei ', time ()-24*60*60 );
    Note that when a Cookie is deleted, its value is still valid on the current page.
Notes for using cookies:
    1. First, it must be set before the HTML file content is output (Cookie is part of the HTTP header, used to transmit information between the browser and the server, therefore, the Cookie function must be called before any HTML file content is output.
On the PHP page, you can use ob_start (); // to enable code ..... Ob_end_flush (); // refresh the cache to prevent header errors );
  1. Different browsers have different Cookie processing mechanisms.
  2. Cookie restrictions are imposed on the client. A browser can create a maximum of 30 cookies, each of which cannot exceed 4 kB. each WEB site can set a maximum of 20 cookies.
  3. The Cookie currently set does not take effect immediately, but will not be visible until the next page.
Session introductionThe session mechanism is a server-side mechanism. the server uses a structure similar to a hash (or a hash) to save information, each website visitor is assigned a unique identifier, that is, the session ID, which is stored in either url-based or client-based Cookies. of course, you can also save the Session to the database, which will be safer, but the efficiency will decrease. the security of url-based transmission must be too poor. the PHP Session mechanism is to set the Cookie, save the session id (Session ID) in the Cookie, and generate a session file on the server, associate with users. Web applications store data related to these sessions and transmit data between pages. PHP functionsThere are many Session-related functions in PHP, but we usually use the following functions: session_start (): enable the session mechanism, call the session program file at the beginning. session_register (): registers the session variable session_unregister (): deletes the session variable (delete one by one) session_is_registered (): determines whether the session variable registers session_distroy (): destroy all session variables (destroy all session variables, including files) Pay attention to the following aspects:1. the session_start () function must be in Program executionLine, there Cannot be any output content before it, otherwise the Warning message "Warning: Cannot send session cookie-headers already sent" similar to this will appear. 2. the session_register () function is used to register related variables to be saved in the session. its usage is as follows: Val is the name of the session variable to be registered. do not add the "$" symbol during registration. just enter the variable name. 3. the session_unregister () function is used exactly the same as the above function, but the function is opposite. the above function registers the session variable, while it deletes the specified session variable. 4. the session_is_registered () function is used to determine whether the session variable is registered. 5. the session_destroy () function is used to destroy all session variables when the system logs out and exits. it has no parameters and can be called directly. Relationship configuration between Session and PHP. ini 1, session. save_handler = fileThe method used to read/write back session data. the default value is files. It allows the PHP session management function to store session data using the specified text file. 2, session. save_path = "/xammp/temp /"Specify the directory for saving the session file. you can specify a directory to another directory. However, the specified directory must have the write permission for the httpd daemon owner (such as apache or www, otherwise, session data cannot be stored back. It can also be written as session. save_path = "N;/path" where N is an integer. In this way, not all session files are stored in the same directory, but are scattered in different directories. This is very helpful for the server to process a large number of session files. (Note: you must manually create a directory) 3, session. auto_start = 0If this option is enabled, the session is initialized for each request. It is not recommended that you use session_start () to initialize the session. : The left side is the session file stored in xammp/tmp/, and the content is the right side of PHP serialization format: the first line is echo serialize ($ _ SESSION ['name']); // The second line of serialization is to print the session value ***************** The file name is session-name, and the content is serialized in PHP format. Differences and relationships between cookies and Sessions
  • Storage location:
    1. The session is stored on the server. you can configure the session configuration in php. ini.
    2. Cookies are stored on the client (in fact, there are two types:
1. Persistent cookie: sets the cookie Time, which is stored on the hard disk as a file. 2. session cookie. If no cookie Time is set, the lifecycle of the cookie disappears before the browser is closed, generally, it is not stored on the hard disk, but in the memory) Relationship between cookie and sessionAs shown in the figure above, the cookie is sent through the http header: Cookie name=PHP%BB%B4%B1%B1; PHPSESSID=cpt2ah3pi4cu7lo69nfbfllbo7 PHPSESSID is an important parameter of the session associated with the server. Check the session File: sess_cpt2ah3pi4cu7lo69nfbfllbo7. The format of session_id is: sess _ plus the value of PHPSESSID. We can understand this as follows:When the program needs to create a session for a client request, the server first checks whether the client request contains a session id (called session id ), if it already exists, it indicates that a session has been created for this client. then, the server retrieves and uses this session according to the session id (a new session will be created if it cannot be retrieved ), if the client request does not contain the session id, the client creates a session and generates a session id associated with the session. the session id value should be unique, the session id is returned to the client for saving in this response. The cookie can be used to save the session id, so that the browser can automatically send the id to the server according to the rules during the interaction. Generally, the cookie name is similar to SEEESIONID. Session and cookie configurations in php. ini1, session. use_cookie = 1
Whether to use the Cookie method to pass the session id value. The default value is 1, indicating that it is enabled.
2, session. name = PHPSESSID
You must use a key value to pass sessioin_id through the Cookie or GET method. Their formats are Cookie: sess_name = session_id; and/path. php? Sess_name = session_id, where sess_name is specified here.
3, session. use_only_cookies = 0
Indicates that only session IDs are transmitted using the Cookie method. As we have said, in addition to cookies, there are also GET methods. the GET method is insecure. When the cookie is disabled on the user side, session_id is transmitted using the GET method. you can use the GET method to pass session_id through this setting.
4. session. cookie_lifetime = 0, session. cookie_path =/, and session. cookie_domain =
If you use the Cookie method to pass session_id, the valid cookie domain, directory, and time are specified here. Corresponds to the $ expire, $ path, and $ domain parameters of the setcookie () function. Cookie_lifetime = 0 indicates that the Cookie is not deleted until the browser is closed. You can also use the session_set_cookie_params () function to modify these values.
5, session_name ([string $ name])
Obtains or updates session_name. If the name is passed, the default name PHPSESSID (specified by session. name) is not used. Otherwise, the current session_name is obtained. Note: If session_name is set, the call takes effect only before session_start.
6, session_id ([string $ id])
Similar to session_name (), but it is the method for reading or setting session_id. Similarly, if session_id is set, it must be called before session_start.
7. session_set_cookie_params () and session_get_cookie_params ()
Session_set_cookie_params () allows you to reset the three php. ini settings: session. cookie_lifetime, session. cookie_path, and session. cookie_domain. Session_get_cookie_params () is used to obtain these set values. Summary:
  1. The cookie security of the server session is higher than that of the client.
  2. Sessions are not synchronized in server clusters, but cookies do not
Ps: In the afternoon, questions about exit using cookiesWhen exiting, use: setcookie ('username', '', time ()-3600 );
Setcookie ('name', '', time ()-3600 );
In theory, the cookie should be cleared normally. during the test, it was found that the first login and exit were completely normal, but the second login would not be able to exit. The cookie always exists and is very depressing. use firebug to check that the original page was set to cache, the reason for setting the page cache with nginx is that

Bytes. Cookies are often used to identify users. Cookie is a server...

Related Article

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.