Php session control session & cookie

Source: Internet
Author: User
: This article mainly introduces php session control sessions & Cookies. For more information about PHP tutorials, see. Cookie introduction

Cookie is the data stored in the client browser. we track and store user data through cookies. Generally, the Cookie is returned from the server to the client through HTTP headers. Most web programs support Cookie operations. Because cookies exist in the HTTP header, they must be set before other information is output, similar to the use restrictions of header functions.

PHP uses the setcookie function to set the Cookie. any Cookie sent back from the browser will automatically store it in the global variable of $ _ COOKIE, therefore, we can read a COOKIE value in the form of $ _ Cookie ['key.

Cookies in PHP are widely used and are often used to store user login information, shopping cart, and so on. In Session, cookies are often used to store Session IDs to identify users, the Cookie has a validity period. after the validity period ends, the Cookie is automatically deleted from the client. At the same time, for security control, Cookie can also set the domain and path. we will explain them in detail in a later chapter.

Set cookie

The most common method for setting a Cookie in PHP is to use the setcookie function. setcookie has seven optional parameters. the first five parameters are commonly used:

Name (Cookie name) can be accessed through $ _ COOKIE ['name ']
Value (Cookie value)
Expire (Expiration Time) Unix timestamp format. the default value is 0, indicating that the browser is disabled or becomes invalid.
Path (valid path) if the path is set to '/', the entire website is valid.
Domain (valid domain) is valid for the entire domain name by default. if 'www .imooc.com 'is set, it is valid only in the www subdomain.

$ Value = 'test'; setcookie ("TestCookie", $ value); setcookie ("TestCookie", $ value, time () + 3600 ); // valid for one hour setcookie ("TestCookie", $ value, time () + 3600, "/path/", "imooc.com"); // set the path and domain

There is also a function setrawcookie in PHP to set cookies. setrawcookie is basically the same as setcookie. The only difference is that the value does not automatically perform urlencode. Therefore, you need to manually perform urlencode when necessary.

Setrawcookie ('cookie _ name', rawurlencode ($ value), time () + 60*60*24*365 );

Because the Cookie is set through the HTTP header, you can also use the header method directly.

Header ("Set-Cookie: cookie_name = value ");

Cookie deletion and Expiration Time

Through the previous chapter, we learned about the cookie setting function, but we found that php does not delete the Cookie function. in PHP, the setcookie function is also used to delete the cookie.

Setcookie ('test', '', time ()-1 );

You can see that the cookie will expire automatically before the current time, so as to delete the cookie. This design is because the cookie is transmitted through the HTTP header. the client sets the Cookie based on the Set-cookie segment returned by the server, if you need to use a new Del-cookie to delete a Cookie, the HTTP header becomes more complex, in fact, you can Set, update, and delete cookies simply and clearly through Set-Cookie.

After understanding the principle, we can also directly delete the cookie through the header.

Header ("Set-Cookie: test = 1393832059; expires = ". gmdate ('d, d m y h: I: s \ G \ M \ t', time ()-1 ));

Gmdate is used to generate Greenwich mean time to eliminate the effect of time difference.

Valid cookie path

The path in the cookie is used to control the path under which the set cookie is valid. the default value is '/', which is available in all paths. after other paths are set, it is only valid under the specified path and sub-path, for example:

Setcookie ('test', time (), 0, '/path ');

The above settings will make test valid in/path and sub-path/abc, but the cookie value of test cannot be read in the root directory.

Generally, all paths are used. The path is set only when there are very few special requirements. in this case, the cookie value is passed only in the specified path, it can save data transmission, enhance security and improve performance.

When we set a valid path, the current cookie will not be visible if it is not in the current path.

Setcookie ('test', '1', 0, '/path'); var_dump ($ _ COOKIE ['test']);

Session and cookie

Cookie stores data on the client and establishes connections between users and servers. it can solve many problems, but cookies still have some limitations:

The cookie is not too secure and is prone to theft, resulting in cookie spoofing.
The maximum value of a single cookie is 4 kB.
Network transmission is required for each request, occupying the bandwidth

Session stores user session data on the server without size restrictions. a session _id is used for user identification. by default, session IDs are saved through cookies in PHP, therefore, to some extent, seesion depends on cookies. However, this is not absolute. The session id can also be implemented through Parameters. as long as the session id can be passed to the server for recognition, the session can be used.

Use session

It is very easy to use session in PHP. first, execute the session_start method to enable the session, and then use the global variable $ _ SESSION to read and write the session.

Session_start (); $ _ SESSION ['test'] = time (); var_dump ($ _ SESSION );

The session automatically performs encode and decode on the value to be set. Therefore, the session can support any data type, including data and objects.

Session_start (); $ _ SESSION ['ary'] = array ('name' => 'job'); $ _ SESSION ['obj '] = new stdClass (); var_dump ($ _ SESSION );

By default, sessions are stored on the server as files. Therefore, when a session is enabled on a page, the session file is exclusive, this will cause other concurrent accesses of the current user to wait for execution. You can use cache or database storage to solve this problem.

Delete and destroy a session

You can use the PHP unset function to delete a session value. after deletion, the value is removed from the global variable $ _ SESSION and cannot be accessed.

Session_start (); $ _ SESSION ['name'] = 'job'; unset ($ _ SESSION ['name']); echo $ _ SESSION ['name']; // the system prompts that the name does not exist.

To delete all sessions, you can use the session_destroy function to destroy the current session. session_destroy deletes all data, but session_id still exists.

Session_start (); $ _ SESSION ['name'] = 'job'; $ _ SESSION ['Time'] = time (); session_destroy ();

It is worth noting that session_destroy does not immediately destroy the value in the global variable $ _ SESSION. $ _ SESSION is empty only when you access it again next time, therefore, you can use the unset function to destroy $ _ SESSION immediately.

Session_start (); $ _ SESSION ['name'] = 'job'; $ _ SESSION ['Time'] = time (); unset ($ _ SESSION ); session_destroy (); var_dump ($ _ SESSION); // null

If you need to destroy session_id in the cookie at the same time, it is usually used when the user exits, you also need to explicitly call the setcookie method to delete the cookie value of session_id.

Use session to store user login information

Sessions can be used to store various types of data. Therefore, sessions are used to store user login information, shopping cart data, or temporary data.

After successful logon, users can usually store their information in Sessions. generally, important fields are stored separately, and all user information is stored independently.

$ _ SESSION ['uid'] = $ userinfo ['uid']; $ _ SESSION ['userinfo'] = $ userinfo;

Generally, login information can be stored in sessioin or cookie. The difference between them is that session can easily access multiple data types, while cookie only supports string types, at the same time, for some highly secure data, the cookie needs to be formatted and encrypted, while the session is stored on the server, which is highly secure.

Session_start ();
// Assume that the user successfully logs on and obtains the following user data
$ Userinfo = array (
'Uid' => 10000,
'Name' => 'Spark ',
'Email '=> 'spark @ imooc.com ',
'Sex '=> 'Man ',
'Age' => '18'
);
Header ("content-type: text/html; charset = utf-8 ");
/* Save user information to the session */
$ _ SESSION ['uid'] = $ userinfo ['uid'];
$ _ SESSION ['name'] = $ userinfo ['name'];
$ _ SESSION ['userinfo'] = $ userinfo;
Echo "welcome". $ _ SESSION ['name'].'
';
// * A simple method for saving user data to cookies */
$ SecureKey = 'imooc '; // encryption key
$ Str = serialize ($ userinfo); // serialize user information
Echo "before user information encryption:". $ str;
$ Str = base64_encode (mcrypt_encrypt (MCRYPT_RIJNDAEL_256, $ secureKey, $ str, MCRYPT_MODE_ECB ));
Echo "after user information is encrypted:". $ str;
// Store encrypted user data in cookies
Setcookie ('userinfo', $ str );
// Decrypt data when necessary
$ Str = mcrypt_decrypt (MCRYPT_RIJNDAEL_256, $ secureKey, base64_decode ($ str), MCRYPT_MODE_ECB );
$ Uinfo = unserialize ($ str );
Echo "decrypted user information:
";
Var_dump ($ uinfo );

Copyright Disclaimer: This article is an original article by the blogger and cannot be reproduced without the permission of the blogger.

The above introduces the php session control session & cookie, including the content, hope to be helpful to friends who are interested in the PHP Tutorial.

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.