search
HomeBackend DevelopmentPHP TutorialThe difference and relationship between cookies and sessions_PHP tutorial
The difference and relationship between cookies and sessions_PHP tutorialJul 13, 2016 am 10:55 AM
cookiesessionandaboutrelationsharethe differenceanddetailedillustrate

Share an article with a detailed explanation of the difference between cookies and sessions. Friends in need can refer to it. It is a very valuable article. Cookies are often used to identify users. Cookies are small files that a server leaves on a user's computer. Whenever the same computer requests a page through the browser, it also sends the cookie. With PHP, you can create and retrieve cookie values. PHP uses the SetCookie function to set cookies. The SetCookie function defines a Cookie and appends it to the end of the HTTP header. The prototype of the SetCookie function is as follows:
int SetCookie(string name, string value, int expire, string path, string domain, int secure);
Parameter description: cookie name, cookie value, expiration time (int), valid path, limited domain name, https delivery is valid

The code is as follows Copy code
 代码如下 复制代码
注意:当前设置的Cookie不是立即生效的,而是要等到下一个页面时才能看到.这是由于在设置的这个页面里Cookie由服务器传递给客户浏览器,在下一个页面浏览器才能把Cookie从客户的机器里取出传回服务器的原因。
Note: The currently set cookie does not take effect immediately, but will not be visible until the next page. This is because the cookie is passed from the server to the client's browser on the page that is set, and the browser will not be able to see it until the next page. The reason for removing the cookie from the client's machine and sending it back to the server.
Usage example: Normal use: setcookie('name','PHP Huaibei'); With expiry time:
setcookie('name','PHP Huaibei',time()+24*60*60);//1day
Cookies are path-oriented and are stored under the current file by default. If the path is not set, cookies under different files are saved in different folders by default, as shown in the figure: By default they are saved in the mytest folder phphuaibei/201111/201111151945348209.png">The difference and relationship between cookies and sessions_PHP tutorial 2. Receive and process Cookies The web communication protocol between the client and the server is http. The three commonly used methods for PHP to obtain user data through http are: POST method, GET method and Cookie. The default delivery method of PHP is Cookie, which is also the best method. For example, if you set a cookie named MyCookier, PHP will automatically analyze it from the HTTP header received by the WEB server and form a variable like an ordinary variable named $myCookie. The value of this variable is the cookie. Value 3. Delete Cookies To delete an existing cookie, there are two ways:
  1. First, call SetCookie with only the name parameter, then the cookie named this name will be deleted from the related computer; for example: setcookie('name','');
  2. Another way is to set the cookie expiration time to time() or time()-1, then the cookie will be deleted (actually invalidated) after the page is browsed. For example: setcookie('name','PHP Huaibei',time()-24*60*60);
    It should be noted that when a cookie is deleted, its value is still valid on the current page.
Notes on using cookies:
    1. First of all, it must be set before the content of the HTML file is output (Cookie is part of the HTTP protocol header and is used to transfer information between the browser and the server, so it must be called before any content belonging to the HTML file itself is output. Cookie function.
You can use it on the PHP page first ob_start();//Start code….. ob_end_flush(); //Refresh cache can prevent header prompt error);
  1. Different browsers handle cookies differently
  2. Cookie restrictions are on the client side. The maximum number of cookies that can be created by a browser is 30, and each cookie cannot exceed 4KB. The total number of cookies that can be set by each WEB site cannot exceed 20.
  3. The currently set cookie does not take effect immediately, but will not be visible until the next page
Session Introduction The session mechanism is a server-side mechanism. The server uses a structure similar to a hash table (or a hash table) to save information. Each website visitor will be assigned a unique identifier, that is, a session ID, its storage form is nothing more than two: either passed through the url, or stored in the cookies of the client. Of course, you can also save the Session in the database, which will be safer, but the efficiency will be reduced. The url method The transfer security is definitely too poor. PHP's session mechanism is to set a cookie and save the session ID (Session ID) in the cookie. A session file will be generated on the server side and associated with the user. The web application stores data related to these sessions. , and transferred between pages. PHP related functions There are many functions related to Session in PHP, but these are the few functions we use most: session_start(): Enable the session mechanism and call it at the beginning of the program file that needs to use the session. session_register(): Register session variable session_unregister(): Delete session variables (one by one) session_is_registered(): Determine whether the session variable is registered session_distroy(): Destroy all session variables (all session variables are destroyed, including files) You need to pay attention to the following aspects: 1. The function session_start() must be executed at the beginning of the program, and there cannot be any output content in front of it, otherwise “Warning:Cannot send session cookie - headers already will appear sent" a warning message like this. 2. The function session_register() is used to register relevant variables to be saved in the session. Its usage is as follows: $val = "session value"; session_register("val"); ?> val is the name of the session variable to be registered. Do not add the "$" symbol when registering, just write the variable name. 3. The function session_unregister() has exactly the same usage as the above function, but has the opposite function. The above function is to register session variable, which deletes the specified session variable. 4. The function session_is_registered() is used to determine whether the session variable is registered. 5. The function session_destroy() is mainly used to destroy all session variables when the system logs out and exits. It has no parameters and can be called directly. Configuration of the relationship between Session and PHP.ini 1,session.save_handler = file The method used to read/write back session data, the default is files. It will cause PHP's session management function to use the specified text file to store session data 2,session.save_path = “/xammp/temp/” Specify the directory to save the session file. You can specify another directory. However, the specified directory must have write permissions from the httpd daemon owner (such as apache or www, etc.), otherwise the session data cannot be restored. It can also be written like session.save_path = "N;/path" where N is an integer. This means that not all session files are saved in the same directory, but are scattered in different directories. This is helpful when the server handles a large number of session files. (Note: The directory needs to be created manually) 3,session.auto_start = 0 If this option is enabled, the session will be initialized for each user request.Not recommended, it is better to initialize the session explicitly through session_start(). The difference and relationship between cookies and sessions_PHP tutorial Above picture: The left side is the session file saved under xammp/tmp/, the content is in PHP serialization format Right side: The first line is echo serialize($_SESSION['name']);//Serialization The second line prints the session value ************************The file name is session-name and the content is in PHP serialized format The difference and relationship between cookie and session
  • Storage location:
    1. The session is stored on the server location, and the session related configuration can be configured through php.ini
    2. Cookies are stored on the client (actually they can be divided into two types:
1. Persistent cookie, the time when the cookie is set, is stored on the hard disk in the form of a file, 2. Session cookie, no cookie time is set, and the life cycle of the cookie is to disappear before closing the browser. Generally, it will not be saved on the hard disk, but on the memory) The relationship between cookie and session The difference and relationship between cookies and sessions_PHP tutorial As you can see from the picture above: Cookie sent via http header: Cookie <font face="Arial">name=PHP%BB%B4%B1%B1; PHPSESSID=cpt2ah3pi4cu7lo69nfbfllbo7<code><font face="Arial">name=PHP%BB%B4%B1%B1; PHPSESSID=cpt2ah3pi4cu7lo69nfbfllbo7</font>
<font face="Arial" size="2">PHPSESSID is an important parameter associated with the server session<code><font face="Arial" size="2">其中PHPSESSID就是关联服务器session的重要参数</font> <font face="Arial" size="2">Look at the session file again: sess_cpt2ah3pi4cu7lo69nfbfllbo7<code><font face="Arial" size="2">再看session文件:sess_cpt2ah3pi4cu7lo69nfbfllbo7</font> <font face="Arial" size="2">The generation format of session_id is: sess_ plus a string of PHPSESSID values<code><font face="Arial" size="2">session_id的生成格式就是:sess_加上一串PHPSESSID的值</font> <font face="Arial" size="2">We can understand it this way: <code><font face="Arial" size="2">我们可以这样理解:</font> When the program needs to create a session for a client's request, the server first checks whether the client's request already contains a session identifier (called session id). If it does, it means that this client has been used before. Once a session is created, the server will retrieve the session and use it according to the session id (if it cannot be retrieved, it will create a new one). If the client request does not include the session id, a session will be created for the client and a session will be generated associated with this session. The session id, the value of the session id should be a string that is neither repeated nor easy to find patterns to counterfeit. This session id will be returned to the client in this response for storage. The method of saving this session ID can use cookies, so that during the interaction process, the browser can automatically send this identification to the server according to the rules. Generally, the name of this cookie is similar to SEEESIONID Configuration related to session and cookie in php.ini 1,session.use_cookie = 1
Whether to use the Cookie method to pass the session id value. The default is 1, which means enabled.
2,session.name = PHPSESSID
Whether the cookie passes sessioin_id or the GET method passes session_id, the key value needs to be used. Their formats are Cookie: sess_name=session_id; and /path.php?sess_name=session_id, where sess_name is specified here.
3,session.use_only_cookies = 0
Indicates that only the session id is passed using the Cookie method. We have said that in addition to cookies, there is also the GET method for passing cookies. The GET method is an unsafe method. When cookies are disabled on the user side, the GET method will be used to pass the session_id. You can use this setting to pass the session_id using the GET method.
4. session.cookie_lifetime = 0, session.cookie_path = / and session.cookie_domain =
If you use the Cookie method to pass session_id, the cookie valid domain, directory and time are specified here. Corresponding to the formal parameters $expire, $path and $domain of the setcookie() function respectively. Among them, cookie_lifetime=0 means that the cookie will not be deleted until the browser is closed. These values ​​can also be modified using the session_set_cookie_params() function.
5,session_name([string $name])
Get or update session_name. If name is passed, it means that the default name PHPSESSID (specified by session.name) is not used, otherwise the current session_name is obtained. Note: If session_name is set, it must be called before session_start() to take effect.
6,session_id([string $id])
Similar to session_name(), but it is a method to read or set session_id. Similarly, if session_id is set, it must be called before session_start() to be effective.
7, session_set_cookie_params() and session_get_cookie_params()
The three php.ini settings of session.cookie_lifetime, session.cookie_path and session.cookie_domain can be reset through session_set_cookie_params(). Session_get_cookie_params() obtains the values ​​of these settings.
Summary:
  1. The server-side session is more secure than the client-side cookie
  2. Session is easily out of sync in a server cluster, but cookies will not
ps: Problems with using cookies to log out this afternoon When exiting use: setcookie('username','',time()-3600);
setcookie('name','',time()-3600);
Theoretically, cookies should be cleared normally. During the test, it was found that the first login and exit were completely normal, but I could not log out after logging in again. The cookie always existed, which was very depressing. I used firebug to check that the original page cache was set, and nginx was used to set the page cache. The reason That is, I found

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/632253.htmlTechArticle Share an article with a detailed explanation of the difference between cookies and sessions. Friends in need can refer to it. It is very valuable. of an article. Cookies are often used to identify users. The cookie is the server...
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尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

mPDF

mPDF

mPDF is a PHP library that can generate PDF files from UTF-8 encoded HTML. The original author, Ian Back, wrote mPDF to output PDF files "on the fly" from his website and handle different languages. It is slower than original scripts like HTML2FPDF and produces larger files when using Unicode fonts, but supports CSS styles etc. and has a lot of enhancements. Supports almost all languages, including RTL (Arabic and Hebrew) and CJK (Chinese, Japanese and Korean). Supports nested block-level elements (such as P, DIV),

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.

WebStorm Mac version

WebStorm Mac version

Useful JavaScript development 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