This article mainly explains the PHP conversation mechanism cookie and session.
Introduction to cookies
Cookies are data stored in the client's 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 the operation of cookies. 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.
PHP sets cookies through the setcookie function. Any cookie sent back from the browser will be automatically stored in the global variable of $_COOKIE by PHP, so we can use $_COOKIE['key' ] to read a cookie value.
Cookies in PHP are very widely used and are often used to store users' login information, shopping carts, etc. When using a Session, Cookies are usually used to store session IDs to identify users. Cookies have a validity period. When the validity period expires, the cookie will be automatically deleted from the client. At the same time, for security control, Cookie can also set domain and path. We will explain them in detail in later chapters.
For the sake of website security, this site does not provide the cookie variable display function for the time being. Please test it locally;
Set cookies
PHP The most common way to set cookies is to use the setcookie function. Setcookie has 7 optional parameters. The first 5 we commonly use are:
name (Cookie name) can be accessed through $_COOKIE['name']
value (Cookie value)
expire (expiration time) Unix timestamp format, the default is 0, which means it will expire when the browser is closed
path (valid path) if If the path is set to '/', the entire website is valid
domain (valid domain) By default, the entire domain name is valid. If 'www.imooc.com' is set, it is only valid in the www subdomain
$value = 'test'; setcookie("TestCookie", $value); setcookie("TestCookie", $value, time()+3600); //有效期一小时 setcookie("TestCookie", $value, time()+3600, "/path/", "imooc.com"); //设置路径与域
There is also a function setrawcookie for setting cookies in PHP. Setrawcookie is basically the same as setcookie. The only difference is that the value will not be automatically urlencoded, so urlencode must be performed manually when needed.
setrawcookie('cookie_name', rawurlencode($value), time()+60*60*24*365);
Because cookies are set through HTTP headers, they can also be set directly using the header method.
header("Set-Cookie:cookie_name=value");
Cookie deletion and expiration time
Through the previous chapters, we learned about the function of setting cookies, but we found that there is no function to delete cookies in php. Deleting cookies in PHP is also achieved using the setcookie function.
setcookie('test', '', time()-1);
You can see that if the expiration time of the cookie is set before the current time, the cookie will automatically expire, thus achieving the purpose of deleting the cookie. The reason for this design is that cookies are passed through HTTP headers. The client sets cookies based on the Set-Cookie segment returned by the server. If deleting cookies requires using a new Del-Cookie, the HTTP header It will become complicated. In fact, the setting, updating and deletion of cookies can be achieved 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 eliminate the impact of time difference.
Session and Cookie Similarities and Differences
Cookie stores data on the client and establishes a connection between the user and the server. It can usually solve many problems, but cookies still It has some limitations:
Cookies are relatively not very secure and can easily be stolen, leading to cookie spoofing
The value of a single cookie can only store a maximum of 4k
Every request requires a network connection Transmission, occupied bandwidth
session stores the user's session data on the server side, with no size limit, and identifies the user through a session_id. By default, PHP session id is saved through a cookie, so from some To a certain 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. .
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']; //提示name不存在
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();
值得注意的是,session_destroy并不会立即的销毁全局变量$_SESSION中的值,只有当下次再访问的时候,$_SESSION才为空,因此如果需要立即销毁$_SESSION,可以使用unset函数。
session_start(); $_SESSION['name'] = 'jobs'; $_SESSION['time'] = time(); unset($_SESSION); session_destroy(); var_dump($_SESSION); //此时已为空
如果需要同时销毁cookie中的session_id,通常在用户退出的时候可能会用到,则还需要显式的调用setcookie方法删除session_id的cookie值。
使用session来存储用户的登录信息
session可以用来存储多种类型的数据,因此具有很多的用途,常用来存储用户的登录信息,购物车数据,或者一些临时使用的暂存数据等。
用户在登录成功以后,通常可以将用户的信息存储在session中,一般的会单独的将一些重要的字段单独存储,然后所有的用户信息独立存储。
$_SESSION['uid'] = $userinfo['uid']; $_SESSION['userinfo'] = $userinfo;
一般来说,登录信息既可以存储在sessioin中,也可以存储在cookie中,他们之间的差别在于session可以方便的存取多种数据类型,而cookie只支持字符串类型,同时对于一些安全性比较高的数据,cookie需要进行格式化与加密存储,而session存储在服务端则安全性较高。
The above is the detailed content of What does php session technology mainly include?. For more information, please follow other related articles on the PHP Chinese website!