search
HomeBackend DevelopmentPHP TutorialPHP cookie and session mechanism

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>

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>
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
修复:谷歌浏览器请求太多错误 429 [已解决]修复:谷歌浏览器请求太多错误 429 [已解决]Apr 16, 2023 am 09:22 AM

近期很多Windows用户反映,当他们尝试访问某个URL时,PC上的GoogleChrome浏览器显示错误429。这是因为每次用户尝试在短时间内通过浏览器。通常,此错误是由网站生成的,以避免通过向服务器发送过多请求而被机器人或黑客入侵病毒。用户对在这个阶段可以做什么感到困惑,并因此感到失望。导致此错误的因素可能很多,我们在下面列出了其中一些因素。缓存内存和其他站点数据未清除从第三方来源安装的扩展系统上的一些有害软件病毒攻击在研究了上面列出的因素之后,我们在这篇文章中收集了一些修复程序,这

如果 Grammarly 无法在 Windows 10 浏览器上运行的 8 个重大修复如果 Grammarly 无法在 Windows 10 浏览器上运行的 8 个重大修复May 05, 2023 pm 02:16 PM

如果您在Windows10或11PC上遇到语法问题,本文将帮助您解决此问题。Grammarly是最流行的打字助手之一,用于修复语法、拼写、清晰度等。它已经成为写作专业人士必不可少的一部分。但是,如果它不能正常工作,它可能是一个非常令人沮丧的体验。许多Windows用户报告说此工具在他们的计算机上运行不佳。我们做了深入的分析,找到了这个问题的原因和解决方案。为什么Grammarly无法在我的PC上运行?由于几个常见原因,PC上的Grammarly可能无法正常工作。它包括以下内

如何修复 Google Chrome 上的 Roblox 403 禁止错误如何修复 Google Chrome 上的 Roblox 403 禁止错误May 19, 2023 pm 01:49 PM

许多Windows用户最近在尝试访问GoogleChrome浏览器中的网站URL时遇到了一个不寻常的错误,称为Roblox403禁止错误。即使在多次重新启动Chrome应用程序后,他们也无能为力。此错误可能有几个潜在原因,我们在下面概述并列出了其中一些。Chrome的浏览历史和其他缓存以及损坏的数据不稳定的互联网连接网站网址不正确从第三方来源安装的扩展在考虑了上述所有方面之后,我们提出了一些修复程序,可以帮助用户解决此问题。如果您遇到同样的问题,请查看本文中的解决方案。修复1

vue3中cookie如何使用vue3中cookie如何使用May 12, 2023 pm 02:19 PM

前言cookie使用最多的地方想必是保存用户的账号与密码,可以避免用户每次登录时都要重新输入1.vue中cookie的安装在终端中输入命令npminstallvue-cookies--save,即可安装cookies,安装之后在main.js文件中写下以下代码import{createApp}from&#39;vue&#39;importVueCookiesfrom&#39;vue-cookies&#39;constapp=createApp(App)app.co

如何在 Google Chrome 中启用或禁用第三方 Cookie如何在 Google Chrome 中启用或禁用第三方 CookieApr 15, 2023 pm 02:07 PM

每个网站都通过创建cookie使用户更容易浏览他们的网页和浏览他们的网站。然而,网站创建了一些第三方cookie,使他们能够跟踪访问其他网站的用户,以便更好地了解他们,从而有助于展示广告和其他帖子。一些用户可能认为他们的数据遭到破坏或存在安全风险,而另一些用户可能认为允许这些第三方cookie跟踪他们以在浏览器上获取更多内容是很好的。所以我们在这篇文章中解释了如何在谷歌浏览器中启用或禁用第三方cookies,详细步骤如下。如何在GoogleChrome中启用第三方Cookie如果您认为要

PHP8.0中的Cookie库PHP8.0中的Cookie库May 14, 2023 pm 04:51 PM

在互联网应用开发中,使用Cookie是常见的一种方式来维护用户会话状态。在PHP语言中,处理Cookie的相关功能在语言的核心库中得到了完善的支持,在最新的PHP8.0版本中,Cookie库得到了进一步的增强。一、PHP中的CookieCookie是一个小文本文件,可以存储在用户的浏览器中,它通常被用来记录用户的个性化设置、登录状态等信息。Cookie是基

php curl怎么设置cookiephp curl怎么设置cookieSep 26, 2021 am 09:27 AM

php curl设置cookie的方法:1、创建PHP示例文件;2、通过“curl_setopt”函数设置cURL传输选项;3、在CURL中传递cookie即可。

如何在ThinkPHP6中使用Cookie技术实现记住我功能如何在ThinkPHP6中使用Cookie技术实现记住我功能Jun 20, 2023 pm 03:33 PM

随着互联网技术的不断发展,越来越多的网站需要用户登录才能使用其功能。但是每次用户访问时都需要输入账号密码显然很不方便,因此“记住我”的功能应运而生。本文将介绍如何在ThinkPHP6中采用Cookie技术实现记住我功能。一、Cookie简介Cookie是一种服务器向客户端发送的小文件,在用户访问网站时存储在用户的计算机上。这些文件包含与用户相关的信息,如登录

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Repo: How To Revive Teammates
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island Adventure: How To Get Giant Seeds
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Atom editor mac version download

Atom editor mac version download

The most popular open source editor

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.