Home > Backend Development > PHP Tutorial > php session control session&cookie

php session control session&cookie

WBOY
Release: 2016-08-08 09:20:04
Original
1062 people have browsed it

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 uses the setcookie function to set cookies. Any cookie sent back from the browser will be automatically stored in the global variable of $_COOKIE by PHP, so we can use the form of $_COOKIE['key'] 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 the session id to identify the user. 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.

Set cookies

The most common way to set cookies in PHP is to use the setcookie function. setcookie has 7 optional parameters, and the first 5 we commonly use are:

name (Cookie name) can be passed $_COOKIE[' name'] to access
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 the path is set to '/ ', the entire website is valid
domain (valid domain) The entire domain name is valid by default. 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 setting in PHP Cookie's function setrawcookie, setrawcookie is basically the same as setcookie. The only difference is that the value value will not be automatically urlencoded, so it must be urlencoded 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. The setcookie function is also used to delete cookies in PHP. accomplish.

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.

Valid path of the cookie

The path in the cookie is used to control which path the set cookie is valid in. The default is '/', which is available in all paths. When other paths are set, then It is only valid under the set path and sub-path. For example:

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

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

Under normal circumstances, most of them use all paths. Only in rare cases where there are special needs, the path will be set. In this case, the cookie value will only be passed in the specified path, which can save data transmission and enhance security and improved performance.

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

setcookie('test', '1',0, '/path'); var_dump($_COOKIE['test']);

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 have some limitations:

Cookies are relatively not It is too safe and easy to be stolen, leading to cookie spoofing
The value of a single cookie can only store up to 4k
Every request requires network transmission, which takes up bandwidth

session是将用户的会话数据存储在服务端,没有大小限制,通过一个session_id进行用户识别,PHP默认情况下session id是通过cookie来保存的,因此从某种程度上来说,seesion依赖于cookie。但这不是绝对的,session id也可以通过参数来实现,只要能将session id传递到服务端进行识别的机制都可以使用session。

使用session

在PHP中使用session非常简单,先执行session_start方法开启session,然后通过全局变量$_SESSION进行session的读写。

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

session会自动的对要设置的值进行encode与decode,因此session可以支持任意数据类型,包括数据与对象等。

session_start(); $_SESSION['ary'] = array('name' => 'jobs'); $_SESSION['obj'] = new stdClass(); var_dump($_SESSION);

默认情况下,session是以文件形式存储在服务器上的,因此当一个页面开启了session之后,会独占这个session文件,这样会导致当前用户的其他并发访问无法执行而等待。可以采用缓存或者数据库的形式存储来解决这个问题。

删除与销毁session

删除某个session值可以使用PHP的unset函数,删除后就会从全局变量$_SESSION中去除,无法访问。

session_start(); $_SESSION['name'] = 'jobs'; unset($_SESSION['name']); echo $_SESSION['name']; //提示name不存在

如果要删除所有的session,可以使用session_destroy函数销毁当前session,session_destroy会删除所有数据,但是session_id仍然存在。

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存储在服务端则安全性较高。

session_start();
//假设用户登录成功获得了以下用户数据
$userinfo = array(
'uid' => 10000,
    'name' => 'spark',
    'email' => 'spark@imooc.com',
    'sex'  => 'man',
    'age'  => '18'
);
header("content-type:text/html; charset=utf-8");
/* 将用户信息保存到session中 */
$_SESSION['uid'] = $userinfo['uid'];
$_SESSION['name'] = $userinfo['name'];
$_SESSION['userinfo'] = $userinfo;
echo "welcome ".$_SESSION['name'] . '
';
//* 将用户数据保存到cookie中的一个简单方法 */
$secureKey = 'imooc'; //加密密钥
$str = serialize($userinfo); //将用户信息序列化
echo "用户信息加密前:".$str;
$str = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_256, $secureKey, $str, MCRYPT_MODE_ECB));
echo "用户信息加密后:".$str;
//将加密后的用户数据存储到cookie中
setcookie('userinfo', $str);
//当需要使用时进行解密
$str = mcrypt_decrypt(MCRYPT_RIJNDAEL_256, $secureKey, base64_decode($str), MCRYPT_MODE_ECB);
$uinfo = unserialize($str);
echo "解密后的用户信息:
";
var_dump($uinfo);

版权声明:本文为博主原创文章,未经博主允许不得转载。

以上就介绍了php会话控制session&cookie,包括了方面的内容,希望对PHP教程有兴趣的朋友有所帮助。

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template