PHP cookie and session mechanism

WBOY
Release: 2016-10-11 14:23:15
Original
989 people have browsed it

Dear masters, I have never been very clear about cookie and session mechanisms. Is there any good information for me to learn from? I would be very grateful

Reply content:

Dear masters, I have never been very clear about cookie and session mechanisms. Is there any good information for me to learn from? I would be very grateful

In fact, if you go to search engines with questions, you will get many answers.
What problems do cookies and sessions solve? How to solve this problem? In fact, once you understand these two problems, you will naturally understand its operating mechanism. Got it.

  1. What problems do cookie and session solve?

It makes up for the inherent flaw of the http protocol, which is stateless (cannot identify whether the previous request and the next request are from the same user).

  1. How to solve it?

Save a key=>value value on the server side, and transmit this key through cookie. Every time the client requests, bring this key to the server side, and the server can distinguish Whether the request comes from the same user.

The above simply answers the mechanism of cookie and session. Specific answers can be searched with these two questions.

Before you understand their implementation principles, first distinguish the roles of the two.

Cookie - a type of cached data that exists in the browser and can be turned off by the browser (in settings). If the browser turns off cookies, the cookies will not be available. Nowadays, generally no one turns off cookies.
Since cookies originate from the browser, Essentially anyone can change your cookies. is it safe? Of course it's not safe. So how can we be safe at this time? Please use Session without exception.

Session - As the name suggests, "session", it is stored on the server, which is different from cookies, which are stored in the user's browser. And it's based on cookies. If the cookie is invalid, the Session will not work properly. Because Session will put its Session_id in Cookie. Each time it communicates with the website server, the server-side programming language can obtain the session_id in the cookie and read the session data stored on the server.
session_id is a very important thing. What should I do if I still want the Session to be useful after cookies are turned off? Each request carries a kv in the header, which provides session_id. . . BLABLABLA. . . I don't think you need to learn this yet, it's just a digression.


COOKIE——The data is stored in the browser currently used by the user (if you change the browser, the previous COOKIE is gone), the security is weak

SESSION - Data is stored on the server with strong security. Changing the browser will also require you to log in again. Because the cookies it relies on are also different depending on the browser.

Next, how to use Cookie and Session? You can learn it.

Session can be implemented based on cookies or get parameters, although it is not safe.
Look at the following example of using MySQL memory table to implement session storage to roughly understand the relationship between session and cookie.

<code>CREATE TABLE sessions (
    user_id int(10) unsigned NOT NULL,
    session text NOT NULL,
    md5 char(32) NOT NULL,
    PRIMARY KEY (user_id)
) ENGINE=MEMORY DEFAULT CHARSET=utf8;
其中:
user_id存储的是用户ID,作为主键.
session存储的是用户的会话数组经过serialize或json_encode后的字符串.
md5存储的是session字段的MD5值,用于实现Check And Set版本号乐观锁:
--读取会话
SELECT session, md5 --写入会话时需要用到这里查出来的md5,就是下面的$last_md5
FROM sessions WHERE user_id = $user_id
--写入会话
UPDATE sessions
SET session = $str, md5 = md5($str)
WHERE user_id = $user_id 
AND md5 = $last_md5 --检查MD5,确保session字段没有被修改过</code>
Copy after login

Implement a customized cookie session mechanism based on the database.
This cookie must not only authenticate users, but also must not be forged and cracked.

<code>//保护用户密码的盐
$salt = sha1(uniqid($user_id.'_'.getmypid().'_'.mt_rand().'_', true));

//数据库保存的用户密码($pwd_user是用户输入的密码明文)
//可以先在浏览器端使用CryptoJS.MD5()哈希密码后传给服务器处理,
//保证服务器对用户密码明文的不知情,最好使用https加密传输避免被窃听和修改.
//数据库保存的用户密码($pwd_user是用户输入的密码明文)
$pwd_db = sha1($salt.sha1($pwd_user));
//password_hash返回值包含盐,这时不需要外部$salt参与.
//password_verify可实现耗时恒定的字符串比较避免时序攻击.
//$pwd_db = password_hash($pwd_user, PASSWORD_DEFAULT);

//cookie里的盐
//其中$global_salt是配置里定义的全局盐,用来保护用户的盐,一旦修改,所有用户的cookie都将失效.
$cookie_salt = sha1($global_salt.sha1($salt));

//最终生成的cookie内容
$cookie = base64_encode($user_id.'|'.$cookie_salt);
//如果你需要高安全性,还可以使用AES(MCRYPT_RIJNDAEL_256)对整个cookie的内容做一次加密.
//$cookie = mcrypt_aes($cookie, $key);

//设置cookie,这里把过期时间设为604800秒(60*60*24*7,一周)
setcookie('sessid', $cookie, time()+604800, '/', '', false, true);

//解密cookie
//$cookie = mdecrypt_aes($_COOKIE['sessid'], $key);

//解码分割后拿到里面的$user_id和$cookie_salt
//根据$user_id查询$salt拼出$cookie_salt,然后跟cookie里的$cookie_salt做对比,一致则通过cookie认证.
$cookie = explode('|', base64_decode($_COOKIE['sessid']));
list($user_id, $cookie_salt) = $cookie;</code>
Copy after login
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!