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 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: |
Copy code |
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. 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 ','');
- 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:
- 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 );
- Different browsers have different Cookie processing mechanisms.
- 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.
- 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: <? Php $ val = "session value"; session_register ("val");?> 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
- The session is stored on the server. You can configure the session configuration in php. ini.
- 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:
- The cookie security of the server session is higher than that of the client.
- 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