Home  >  Article  >  Backend Development  >  Cookies and sessions in PHP

Cookies and sessions in PHP

怪我咯
怪我咯Original
2017-01-16 11:01:561963browse

In PHP, there are two very important functions, which are our cookie and session. So how are they used and what is the difference?

This article will take you to understand cookies and sessions

Introduction to cookies

Cookies are data stored in the client browser. We use cookies to track and store User data. Typically, cookies are returned from the server to the client via 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 usage restrictions of the header function.

Set cookie method

setcookie("name",'zhangsan');

setcookie("name",'zhangsan',time()+60);/ /Set the cookie validity time to 60 seconds

//setcookie("visittime",date("y-m-d H:i:s"),time()+60);//Set the variable that saves the cookie expiration time

Read cookie method

$name=$_COOKIE["name"};

Delete cookie method

setcookie("name","" ,time()-1);//Set the time of cookie() to the current time minus 1. The time() function returns the current timestamp expressed in seconds. Subtracting 1 second from the expiration time will get the past time, so Delete cookie

To delete cookiez, you only need to set the second parameter in the setcookie() function to a null value, and set the expiration time of the third parameter cookie to be less than the current time of the system

Cookies and sessions in PHP

After understanding cookies, let’s take a look at session

session stores the user’s session data on the server, with no size limit, through a session_id is used for user identification. By default, PHP session id is saved through cookies, so to some extent, seesion relies on cookies. But 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 identification, the session can be used.

Using session

Using session in PHP is very simple. First execute the session_start method to open the session, and then read and write the session through the global variable $_SESSION.

session_start();$_SESSION['test'] = time();var_dump($_SESSION);

session will automatically encode and decode the value to be set, so 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, sessions are stored on the server in the form of files. Therefore, when a session is opened on a page, the session file will be exclusively occupied. This will cause other concurrent accesses of the current user to be unable to execute and wait. This problem can be solved by using cache or database storage, which we will talk about in some advanced courses.

Delete and destroy session

To delete a session value, you can use PHP's unset function. After deletion, it will be removed from the global variable $_SESSION and cannot be accessed.

session_start();$_SESSION['name'] = 'jobs';unset($_SESSION['name']);echo $_SESSION['name']; //Prompt 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 will delete all data, but the session_id still exists.

session_start();$_SESSION['name'] = 'jobs';$_SESSION['time'] = time();session_destroy();

It is worth noting that session_destroy The value in the global variable $_SESSION will not be destroyed immediately. Only when it is accessed next time, $_SESSION will be empty. Therefore, 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); //It is empty at this time

If you need to destroy the session_id in the cookie at the same time, which may usually be used when the user logs out, you also need to explicitly call the setcookie method to delete the cookie value of session_id.

Use session to store user login information

Session can be used to store many types of data, so it has many uses. It is often used to store user login information, shopping cart data, or Some temporary data for temporary use, etc.

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

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

Generally speaking, login information can be stored in sessioin , or can be stored in cookies. The difference between them is that session can easily access multiple data types, while cookies only support string types. At the same time, for some data with higher security, cookies need to be formatted and Encrypted storage, and session storage on the server side is more secure.

header("content-type:text/html; charset=utf-8");

session_start();//Assume that the user logs in successfully and obtains the following user data $userinfo = array(

'uid' => 100,

'name' => 'liu',

'email' => '123456789@qq.com',

'sex' => 'man',

'age' => '23');

/* Save user information to session*/

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

$_SESSION['name'] = $userinfo['name'];

$_SESSION ['userinfo'] = $userinfo;

//* A simple way to save user data to cookies*/

$secureKey = 'php';

//Encryption key $str = serialize($userinfo);

//Serialize user information //Before encrypting user information

$str = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, md5( $secureKey), $str, MCRYPT_MODE_ECB));

//After encrypting user information//Storing the encrypted user data into cookies

setcookie('userinfo', $str) ;

?>

Cookies and sessions in PHP

Finally, let’s take a look at the biggest difference between session and cookie:

First, session is session The information is stored on the server, and the client's information is transmitted through a session ID. At the same time, after the server receives the session ID, it provides relevant session information resources based on this ID.

Secondly, the cookie combines all the information with The form of text is saved on the client and managed and maintained by the browser

3. Since the session is stored on the server, all remote users cannot modify the content of the session file, and the cookie

is a client End storage, all sessions are much more secure than cookies, and of course there are many advantages, such as easy control, customizable storage, etc. (stored in the database)...


Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn