PHP Session control (Session&cookie)

Source: Internet
Author: User
Tags session id php session setcookie urlencode

Cookie Introduction

Cookies are data stored in the client's browser, and we use cookies to track and store user data. In general, cookies are returned from the server to the client via HTTP headers. Most Web programs support the operation of cookies because the cookie is in the header of HTTP, so it must be set before other information output, similar to the use limit of the header function.

PHP uses the Setcookie function to set the COOKIE, and any cookie,php sent back from the browser will automatically store it in the $_cookie global variable, so we can pass the $_cookie[' key ' To read a cookie value in the form of a

Cookies in PHP are very widely used, often used to store users ' login information, shopping carts, etc., and often use cookies to store session IDs to identify users when using session sessions, and the cookie has an expiration date, The cookie is automatically removed from the client. Cookies can also set domain and path for security control, and we will explain them in detail in a later section.

Set cookies

The most common way to set up cookies in PHP is to use the Setcookie function, Setcookie has 7 optional parameters, which we commonly used for the first 5:

name ( cookie name) can be accessed via $_cookie[' name ']
value (value of the COOKIE)
expire (Expiration Time) UNIX timestamp format, default is 0, which means that the browser is off and expires
path (valid path) if the path is set to '/', the entire site is valid

$value = ' test '; Setcookie ("TestCookie", $value), Setcookie ("TestCookie", $value, Time () +3600);  Valid for one hour Setcookie ("TestCookie", $value, Time () +3600, "/path/", "imooc.com"); Set path and domain

PHP also has a function to set the cookie Setrawcookie,setrawcookie is basically the same as Setcookie, the only difference is that value values are not automatically urlencode, It is therefore necessary to manually carry out the urlencode when needed.

Because cookies are set by HTTP headers, they can also be set directly using the header method.

Header ("Set-cookie:cookie_name=value");
Deletion and expiry time of cookies

In the previous chapters, we learned about the function of setting cookies, but we found that PHP does not have a function of deleting cookies, and that deleting cookies in PHP is also done using the Setcookie function.

You can see that the cookie expires before the current time, and the cookie is automatically invalidated and the cookie is deleted. The reason for this is that the cookie is passed through the HTTP header, the client sets the cookie based on the Set-cookie segment returned by the server, and if the cookie needs to be implemented with a new Del-cookie, the HTTP header becomes complex. In fact, the cookie can be set up, updated and deleted simply and clearly through Set-cookie.

After understanding the principle, we can also delete cookies directly 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 here to generate Greenwich Mean time to rule out the effects of jet lag.

Valid path for cookies

The path in the cookie is used to control which path the cookie is set to be valid, the default is '/', under all paths, and when another path is set, it is only valid in the path and sub-path set, for example:

Setcookie (' Test ', Time (), 0, '/path ');

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

In general, most of the use of all paths, only in a very small number of special needs, will set the path, in this case only in the specified path to pass the cookie value, can save data transmission, enhance security and improve performance.

When we set a valid path, we do not see the current cookie at the current path.

Setcookie (' Test ', ' 1 ', 0, '/path ');  Var_dump ($_cookie[' test ');  
The similarities and differences between session and Cookie

Cookies store data on the client and establish a connection between the user and the server, which can often solve many problems, but the cookie still has some limitations:

Cookies are relatively less secure and easily compromised to cause cookie spoofing
The maximum value of a single cookie can only be stored 4k
Network transfer for each request, consuming bandwidth

Session data is stored on the server server, no size limit, through a session_id user identification, PHP by default, the session ID is saved through a cookie, so in a way, seesion relies on cookies. But this is not absolute, the session ID can also be implemented by parameters, as long as the session ID can be passed to the server to identify the mechanism can use the session.

Use session

Using the session in PHP is very simple, first executing the Session_Start method to open the session, and then through the global variable $_session session read and write.

Session_Start (); $_session[' test '] = time (); Var_dump ($_session);

The session automatically encode and decode the values to be set, so the session can support any data type, including data and objects.

Session_Start (); $_session[' ary '] = array (' name ' = ' Jobs '); $_session[' obj '] = new StdClass (); Var_dump ($_session);

By default, the session is stored as a file on the server, so when a page opens the session, it will monopolize the session file, which will cause other concurrent accesses of the current user to be unable to execute and wait. It can be stored in the form of a cache or a database to solve this problem.

Delete and destroy session

Deleting a session value can use PHP's unset function, which is removed from the global variable $_session and cannot be accessed.

Session_Start (); $_session[' name '] = ' jobs '; unset ($_session[' name '); Echo $_session[' name ']; Hint name does not exist

If you want to delete all sessions, you can use the Session_destroy function to destroy the current Session,session_destroy delete all data, but session_id still exists.

Session_Start (); $_session[' name '] = ' jobs '; $_session[' time ' = time (); Session_destroy ();

It is important to note that Session_destroy does not immediately destroy the value in the global variable $_session, but only when the next time it is accessed, $_session is empty, so if you need to destroy $_session immediately, you can use the unset function.

Session_Start (); $_session[' name '] = ' jobs '; $_session[' time ' = time (); unset ($_session); Session_destroy (); Var_dump ($_session); This is now empty

If it is necessary to destroy the session_id in the cookie at the same time, usually when the user exits, it is also necessary to explicitly call the Setcookie method to remove the session_id cookie value.

Use session to store user's login information

Session can be used to store multiple types of data, so it has a lot of uses, commonly used to store user login information, shopping cart data, or some temporary use of staging data.

After the user has successfully logged in, the user's information can usually be stored in the session, the general will separate some important fields stored separately, and then all the user information stored independently.

$_session[' uid '] = $userinfo [' uid '];$_session[' userinfo '] = $userinfo;

In general, the login information can be stored in the Sessioin, but also stored in the cookie, the difference between them is that the session can easily access a variety of data types, and the cookie only supports string type, while for some security relatively high data, Cookies need to be formatted and encrypted, and session storage is more secure on the server side.

<?php
Session_Start ();
Assuming the user is logged on successfully, the following user data is obtained
$userinfo = Array (
' UID ' = 10000,
' Name ' = ' spark ',
' Email ' = ' [email protected] ',
' Sex ' = ' man ',
' Age ' = ' 18 '
);
Header ("content-type:text/html; Charset=utf-8 ");


/* Save the user information to the session */
$_session[' uid '] = $userinfo [' uid '];
$_session[' name '] = $userinfo [' name '];
$_session[' userinfo '] = $userinfo;
echo "Welcome". $_session[' name ']. ' <br> ';


* A simple way to save user data to a cookie */
$secureKey = ' IMOOC '; Encryption key
$str = serialize ($userinfo); Serialization of user information
echo "User information before encryption:". $str;
$str = Base64_encode (Mcrypt_encrypt (mcrypt_rijndael_256, $secureKey, $str, MCRYPT_MODE_ECB));
echo "User Information encrypted:" $STR;
Store encrypted user data in a cookie
Setcookie (' UserInfo ', $str);


Decrypt when needed for use
$str = Mcrypt_decrypt (mcrypt_rijndael_256, $secureKey, Base64_decode ($STR), MCRYPT_MODE_ECB);
$uinfo = Unserialize ($STR);
echo "Decrypted user information:<br>";
Var_dump ($uinfo);


Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

PHP Session control (Session&cookie)

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.