PHP Cookie and session mechanism

Source: Internet
Author: User
Tags sha1
Dear God, I am not particularly clear about the cookie and the session mechanism, there is no good information for me to learn, grateful

Reply content:

Dear God, I am not particularly clear about the cookie and the session mechanism, there is no good information for me to learn, grateful

In fact, you take the problem to search engines, will come up with a lot of answers.
What problems does the cookie and session solve? How to solve this problem? In fact, it is clear that these two problems, its operating mechanism you will naturally understand.

    1. What problems does the cookie and session solve?

Make up for the inherent flaw of the HTTP protocol, stateless (unable to identify whether the last request and the next request are from the same user).

    1. What's the deal?

Save a value on the server side key=>value and key transfer it through a cookie. Each time the client requests, take this to the key server side, the server can distinguish whether the request from the same user.

The above is simply an answer to the cookie and session mechanism. Specific answers can be searched with these two questions.

Before you know the principles of their implementation, make a distinction between the 2 characters.

cookie--a cached data that exists in the browser and can be closed by the browser (in Settings). If the browser is turned off, Cookie,cookie will not be available. No one is going to turn off cookies now.
Since a cookie comes from a browser, virtually anyone can move your cookie. Is it safe? Not safe, of course. So how is this time safe? Please use the session with no exceptions.

session--as the name implies "session", it is stored on the server, which is different from the cookie is stored in the user's browser. And it's cookie-based. If the cookie is invalid, the session will not work properly. Because the session will put its own session_id in the cookie. Each time you communicate with the Web server, the server-side program language can obtain this session_id in the cookie to read the session data stored on the server.
SESSION_ID is a very important thing. What if I want sesion to be useful after the cookie is closed? Each request has a KV in the header, which provides session_id ... Blablabla ... I don't think you need to study this right now, it's just off the topic.

cookie--data is stored in the browser currently used by the user (for a browser, before the cookie is gone OH), the security is weak

session--data is stored on the server, security is strong. A different browser will also require you to log in again. Because it relies on the cookie also because of the browser's sake different.

Next, how to use cookies and session? You can learn the next.

Sessions can be implemented based on a cookie or can be implemented based on a get parameter, although not secure.
Take a look at the following example of using MySQL memory table to implement session storage you probably know the relationship between session and Cookie.

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_md5FROM sessions WHERE user_id = $user_id--写入会话UPDATE sessionsSET session = $str, md5 = md5($str)WHERE user_id = $user_id AND md5 = $last_md5 --检查MD5,确保session字段没有被修改过

Implement a set of custom cookie session mechanism based on database.
This cookie is not only to authenticate users, but also to be able to be forged and cracked.

The salt $salt to protect the user's password = SHA1 (Uniqid ($user _id. _ '. Getmypid (). ' _ '. Mt_rand (). ' _ ', true));//The user password saved by the database ($pwd _user is the user input password plaintext)//You can first use CRYPTOJS.MD5 () hash password on the browser side to the server processing,//To ensure that the server is not aware of the user password plaintext, It is best to use HTTPS encrypted transmission to avoid eavesdropping and modification.//The user password saved by the database ($pwd _user is the password plaintext entered by the user) $pwd _db = SHA1 ($salt. SHA1 ($pwd _user));//password_ The hash return value contains salt and does not require an external $salt to participate.//password_verify can achieve time-consuming and constant string comparisons to avoid timing attacks.//$pwd _db = Password_hash ($pwd _user, Password_ DEFAULT); The salt in the//cookie//The $global_salt is a global salt defined in the configuration to protect the user's salt, and once modified, all user's cookies will expire. $cookie _salt = SHA1 ($global _ SALT.SHA1 ($salt));//The resulting cookie content $cookie = Base64_encode ($user _id. ' | '. $cookie _salt);//If you need high security, you can also use AES (MCRYPT_RIJNDAEL_256) to encrypt the contents of the entire cookie once.//$cookie = Mcrypt_aes ($cookie, $key);// Set the cookie, where the expiration time is set to 604,800 seconds (60*60*24*7, one week) Setcookie (' Sessid ', $cookie, Time () +604800, '/', ' ", false, true);//Decrypt Cookie $cookie = Mdecrypt_aes ($_cookie[' sessid '), $key);//decode to get inside the $user_id and $cookie_salt//according to $user_id query $salt spell $cookie_ Salt, and then contrast it with the $cookie_salt in the cookie, which is certified by the cookie. $cookie = Explode (' | ', Base64_decode ($_cookie[' sessid]) List ($user _id, $cookie _salt) = $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.