search
HomeBackend DevelopmentPHP TutorialPHP version--HTTP session cookie principle and application

PHP’s COOKIE

Cookie is a mechanism that stores data on the remote browser side to track and identify users.
PHP sends cookies in the header information of the http protocol, so the setcookie() function must be called before other information is output to the browser, which is similar to the restriction on the header() function.

--------------------------------------------- -------------------------------------------------- ----------------------------------

1. Set cookie:

a .You can use the setcookie() or setrawcookie() function to set cookies. It can also be set by sending http headers directly to the client.

eg:

Php code PHP version--HTTP session cookie principle and application

  1. $value = 'something from somewhere';
  2. setcookie( "TestCookie", $value); /* Simple cookie settings */
  3. setcookie("TestCookie", $value, time( )+3600); /* Validity period 1 hour */
  4. setcookie("TestCookie", $value, time()+3600, "/ ~rasmus/",
  5. ".example.com", 1); /* Valid directory /~rasmus, valid domain name example.com and all its subdomains */

Set multiple cookies Variables: setcookie('var[a]','value'); Use an array to represent variables, but do not use quotation marks for his subscripts. In this way, you can use $_COOKIE[‘var’][‘a’] to read the COOKIE variable.

b. Use header() to set cookies;

header("Set-Cookie: name=$value[;path=$path[;domain=xxx.com[ ;...]]");

eg:

Php code

PHP version--HTTP session cookie principle and application

  1. $value = 'something from somewhere';
  2. header("Set-Cookie:name=$value"); -------------------------------------------------- -------------------------------------------------- -------------
  3. 2. Read cookies:

You can read browser-side cookies directly using PHP's built-in super global variable $_COOKIE.

The cookie "TestCookie" is set in the above example, now let's read:

eg:

Php code

  1. print $_COOKIE['TestCookie'];

-------------------------------- -------------------------------------------------- -------------------------------------------------- --------

3.Delete cookie

Just set the valid time to be less than the current time, and set the value to empty. For example:

eg:

Php code PHP version--HTTP session cookie principle and application

  1. setcookie("name", " ", time()-1);

Use header() similar.

Note:

a.There is an error message when using setcookie(). It may be because there is output or space before calling setcookie(). It is also possible that your document was converted from another character set. On the other hand, the document may have a BOM signature (that is, adding some hidden BOM characters to the file content). The solution is to prevent this from happening in your document. You can also handle it a little bit by using the ob_start() function.

b.$_COOKIE is affected by magic_quotes_gpc and may be automatically escaped

c.When using it, it is necessary to test whether the user supports cookies

- -------------------------------------------------- -------------------------------------------------- ------------------------

4. Principle.

a. The server sends an http with the response Set-Cookie header, sets a cookie in the client (multiple cookies require multiple headers).

b. The client automatically sends an http cookie header to the server, and the server receives and reads it.
HTTP/1.x 200 OK
MT
                                Cache -Control: no-store, no-cache, must-revalidate, post-check=0, pre-check=0
                                                                                                          use using using using ’ ’ s ’ s ’ s ‐   ‐ ‐ ‐ t , after receiving this line


Set-Cookie: TestCookie=something from somewhere; path=/

The browser will create a cookie file on the client’s disk and write in it:

TestCookie=something from somewhere;


This line is the result of us using setcookie('TestCookie','something from somewhere','/'); That is the result of using

header('Set-Cookie: TestCookie=something from somewhere; path=/');.


---------------------------------------- ---------Dividing line--------------------------------------- --------------------------------

PHP SESSION

session uses a cookie with an expiration time set to 0, and generates a unique identifier (a long string) called session ID synchronously on the server side. session file (you can define the saving type of the session yourself), associated with the user machine. The web application stores data related to these sessions and allows the data to be passed between pages with the user. Visitors to the website are assigned a unique identifier, a so-called SESSION ID. It is either stored in a cookie on the client side or passed via the URL. SESSION allows the user to register any number of variables and reserve them for each request. When a visitor accesses the website, PHP automatically (if session.auto_start is set to 1) or at the user's request (explicitly called by session_start() or session_register() Called implicitly) to check if a specific SESSION ID was sent in the request. If so, the previously saved environment is recreated.

The core concept of session is: extra data for jumping between web pages is saved on the server and identified by an ID. To maintain the session, the browser needs to bring this ID with each submission.

------------------------------------------------ -------------------------------------------------- ----------------------------------

There are two ways to pass session id:

a. Transmit the SESSION ID through cookies

Use session_start() to call the session. The server generates the session while generating the session file. ID hash value and session name with default value of PHPSESSID, and the variable sent to the client is (default is) PHPSESSID(session name), and the value is a 128-bit hash value. The server will interact with the client through this cookie. The value of the session variable is serialized internally by PHP and stored in a text file on the server machine. It interacts with the client's coolie whose variable name is PHPSESSID by default. That is, the server automatically sends the http header: header('Set-Cookie : session_name()=session_id(); path=/'); i.e. setcookie(session_name(),session_id());
When you jump to a new page from this page and call session_start(), PHP will check the server-side storage associated with the given ID session data, if not found, create a new data set.

b.Transmit session ID through URL

This method is only used when the user prohibits the use of cookies, because browser cookies are already universal, and for security reasons, they are not used. this method.
xxx, session can also be passed through POST value.

--------------------------------------------- -------------------------------------------------- ----------------------------------

If the client prohibits the use of cookies, you can use the following Method:

a. Set session.use_trans_sid = 1 in php.ini or turn on the --enable-trans-sid option when compiling to let PHP automatically pass the session id across pages.
b. Manually pass the value through the URL and pass the session id through the hidden form.
c. Save session_id in a file, database, etc., and call it manually during the cross-page process.

link: http://apps.hi.baidu.com/share/detail/41643457

session can also be used when cookies are disabled: session.use_cookies in
php.ini =1, change it to 0, the session will be saved on the server side, not the client's cookie.

You can view the server's session storage location through session.save_path

session usage:

eg:

Php code PHP version--HTTP session cookie principle and application

  1. // page1.php
  2. session_start();
  3. echo 'Welcome to page #1';
  4. /* Create session variable and assign value to session variable */
  5. $_SESSION ['favcolor'] = 'green' ;
  6. $_SESSION['time '] = time ();
  7. echo '< ;br />page 2';
  8. // If the client disables cookies
  9. echo '
    page 2'
  10. ;
  11. /*
  12. By default under php5.2.1, the SID will only have a value when the cookie is written. If the session The corresponding cookie already exists , then the SID will be (undefined) empty
  13. hp code
  14. // page2 .php
  15. session_start();
  16. print $_SESSION['animal'
]; //Print out a single session

PHP version--HTTP session cookie principle and application var_dump(

$_SESSION
    );
  1. //Print out the session value passed by page1.php
  2. Delete session:
  3. eg:Php code
session_dest roy(); //The first step: Delete the server-side session file , this uses

setcookie(session_name(),

'',time()-3600);

// Step 2: Delete the actual session:

$_SESSION

=

arrayPHP version--HTTP session cookie principle and application();

// Step 3: Delete $_SESSION global variable array
  1. ?>
  2. ------------------------ -------------------------------------------------- -------------------------------------------------- --

    A simple example:

    php code:

    Php code PHP version--HTTP session cookie principle and application

    1. session_start();
    2. if (isset($_SESSION['test_sess'])){
    3. $_SESSION['test_sess ']++;
    4. $_SESSION
    5. ['test_sess'
    6. ] = 0;
    7. } echo
    8. $_SESSION['test_sess' ; First request to server:
    9. GET /test.php HTTP/1.1
    10. Accept: */*
    11. Referer: http://localhost/ Accept-Language: zh-cn Accept-Encoding: gzip, deflate User-Agent : Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322) Host: localhost
    12. Connection: Keep-Alive
    13. Server No. Return once: HTTP/1.1 200 OK Date: Fri, 26 Aug 2005 07:44:22 GMT
    14. Server: Apache/2.0.54 (Win32) SVN/1.2.1 PHP / 5.0.4 DAV/2
    X-Powered-By: PHP/5.0.4 Set-Cookie: PHPSESSID=bmmc3mfc94ncdr15ujitjogma3; path=/

    Expires: Thu, 19 Nov 1981 08:52:00 GMT Cache-Control : no -store, no-cache, must-revalidate, post-check=0, pre-check=0 Pragma: no-cache

    Content-Length: 1

    Keep-Alive: timeout=15, max=99 Connection: Keep -Alive Content-Type: text/html; charset=utf-8 Content-Language: Off

    Second request to the server:



    GET /test.php HTTP/1.1
    Accept: */*
    Referer: http://localhost/
    Accept-Language: zh-cn
    Accept-Encoding: gzip, deflate
    User-Agent: Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; Maxthon; .NET CLR 1.1.4322)
    Host: localhost
    Connection: Keep-Alive
    Cookie: PHPSESSID=bmmc3mfc94ncdr15ujitjogma3

    Second server Returns:

    HTTP/1.1 200 OK
    Date: Fri, 26 Aug 2005 07:44:23 GMT
    Server: Apache/2.0.54 (Win32) SVN/1.2.1 PHP/5.0.4 DAV/2
    X- Powered-By: PHP/5.0.4
    Set-Cookie: PHPSESSID=bmmc3mfc94ncdr15ujitjogma3; path=/
    Expires: Thu, 19 Nov 1981 08:52:00 GMT
    Cache-Control: no-store, no-cache, must- revalidate, post-check=0, pre-check=0
    Pragma: no-cache
    Content-Length: 1
    Keep-Alive: timeout=15, max=98
    Connection: Keep-Alive
    Content-Type: text/ html; charset=utf-8
    Content-Language: OFF
    This The header will send a cookie information to the server, telling the server that I have a cookie named PHPSESSID and the content is bmmc3mfc94ncdr15ujitjogma3.
    Where did this cookie come from? Look at the information returned by the server for the first time:
    Set-Cookie: PHPSESSID=bmmc3mfc94ncdr15ujitjogma3; path=/

    This is the server writing a cookie to the client browser. The name is PHPSESSID and the value is bmmc3mfc94ncdr15ujitjogma3. This value is actually the so-called session_id.

    Continue to look at the second request to the server, and the cookie PHPSESSID is still sent to the server The following conclusions can be drawn: 1. As long as the session is used, the session will be sent to the client browser through the cookie

    2. Every time a request is made to the server, the local browser will attach the cookie to the request information. Sending session

    In fact, session is a completely abstract concept. What session really does is, in addition to the parameters provided by http and post, is to target a user (maybe a browser, or a computer, or even It is an IP) that can save additional information. If we don't use the session provided by the system, we can also transfer data. For example, the data we originally want to store in the session can be serialized and then encrypted to form a string and passed in all URLs and forms on the page. After the server receives the page request, it takes out the secret string from get or post, uncovers it, and restores the data. This is actually the same thing as the session. It's just that this method is super bt, and it requires too much extra work to implement. From a technical point of view, session is to name the additional data to be stored between web page links with an ID and save it on the server side. The browser only needs to provide the appropriate ID for each get or post. Can obtain previously stored data. PHP uses files to save data by default. Under Unix, PHP will generally create a file name like "sess_"+$session_id under /tmp. Through this name, you can directly find the data corresponding to session_id. Therefore, the most core concept of session is: additional data for jumping between web pages is stored on the server and identified with an ID. To maintain the session, the browser needs to bring this ID with each submission.
    How can the browser bring this ID with every request? The stupid way is of course to add an ID parameter to each URL link or form post. Some webmails actually do this. Of course, the easier way is to save it through cookies. But there is still a problem with the cookie solution. What to do if the browser does not support cookies? This is also stated above. The above session is the session function provided by php4 and 5. You must know that the system did not provide the session function before php4! And many cgi programs are completely self-implemented sessions. For sessions provided by php(4,5), the system will use cookies to save session_id by default. In my previous project, users all used the web on the intranet. In order to facilitate management, the browser IP is directly tied to a session, that is, the browser IP address is used instead of the sessionid. There is no cookie in this solution, but it is still a session, because it does not fall outside the definition of session.







    Every time a request is made to the server, the local browser will attach the cookie to the request information
    In fact, it has nothing to do with the session, it is just about how cookies work in the http protocol. This cookie is written by the session_start() function. We can also write the cookie arbitrarily. As long as it is written and the validity period has not expired, the browser can send it.

    The above introduces the PHP version - HTTP session cookie principle and application, including the relevant content. I hope it will be helpful to friends who are interested in PHP tutorials.

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
解决方法:您的组织要求您更改 PIN 码解决方法:您的组织要求您更改 PIN 码Oct 04, 2023 pm 05:45 PM

“你的组织要求你更改PIN消息”将显示在登录屏幕上。当在使用基于组织的帐户设置的电脑上达到PIN过期限制时,就会发生这种情况,在该电脑上,他们可以控制个人设备。但是,如果您使用个人帐户设置了Windows,则理想情况下不应显示错误消息。虽然情况并非总是如此。大多数遇到错误的用户使用个人帐户报告。为什么我的组织要求我在Windows11上更改我的PIN?可能是您的帐户与组织相关联,您的主要方法应该是验证这一点。联系域管理员会有所帮助!此外,配置错误的本地策略设置或不正确的注册表项也可能导致错误。即

Windows 11 上调整窗口边框设置的方法:更改颜色和大小Windows 11 上调整窗口边框设置的方法:更改颜色和大小Sep 22, 2023 am 11:37 AM

Windows11将清新优雅的设计带到了最前沿;现代界面允许您个性化和更改最精细的细节,例如窗口边框。在本指南中,我们将讨论分步说明,以帮助您在Windows操作系统中创建反映您的风格的环境。如何更改窗口边框设置?按+打开“设置”应用。WindowsI转到个性化,然后单击颜色设置。颜色更改窗口边框设置窗口11“宽度=”643“高度=”500“&gt;找到在标题栏和窗口边框上显示强调色选项,然后切换它旁边的开关。若要在“开始”菜单和任务栏上显示主题色,请打开“在开始”菜单和任务栏上显示主题

如何在 Windows 11 上更改标题栏颜色?如何在 Windows 11 上更改标题栏颜色?Sep 14, 2023 pm 03:33 PM

默认情况下,Windows11上的标题栏颜色取决于您选择的深色/浅色主题。但是,您可以将其更改为所需的任何颜色。在本指南中,我们将讨论三种方法的分步说明,以更改它并个性化您的桌面体验,使其具有视觉吸引力。是否可以更改活动和非活动窗口的标题栏颜色?是的,您可以使用“设置”应用更改活动窗口的标题栏颜色,也可以使用注册表编辑器更改非活动窗口的标题栏颜色。若要了解这些步骤,请转到下一部分。如何在Windows11中更改标题栏的颜色?1.使用“设置”应用按+打开设置窗口。WindowsI前往“个性化”,然

OOBELANGUAGE错误Windows 11 / 10修复中出现问题的问题OOBELANGUAGE错误Windows 11 / 10修复中出现问题的问题Jul 16, 2023 pm 03:29 PM

您是否在Windows安装程序页面上看到“出现问题”以及“OOBELANGUAGE”语句?Windows的安装有时会因此类错误而停止。OOBE表示开箱即用的体验。正如错误提示所表示的那样,这是与OOBE语言选择相关的问题。没有什么可担心的,你可以通过OOBE屏幕本身的漂亮注册表编辑来解决这个问题。快速修复–1.单击OOBE应用底部的“重试”按钮。这将继续进行该过程,而不会再打嗝。2.使用电源按钮强制关闭系统。系统重新启动后,OOBE应继续。3.断开系统与互联网的连接。在脱机模式下完成OOBE的所

Windows 11 上启用或禁用任务栏缩略图预览的方法Windows 11 上启用或禁用任务栏缩略图预览的方法Sep 15, 2023 pm 03:57 PM

任务栏缩略图可能很有趣,但它们也可能分散注意力或烦人。考虑到您将鼠标悬停在该区域的频率,您可能无意中关闭了重要窗口几次。另一个缺点是它使用更多的系统资源,因此,如果您一直在寻找一种提高资源效率的方法,我们将向您展示如何禁用它。不过,如果您的硬件规格可以处理它并且您喜欢预览版,则可以启用它。如何在Windows11中启用任务栏缩略图预览?1.使用“设置”应用点击键并单击设置。Windows单击系统,然后选择关于。点击高级系统设置。导航到“高级”选项卡,然后选择“性能”下的“设置”。在“视觉效果”选

Windows 11 上的显示缩放比例调整指南Windows 11 上的显示缩放比例调整指南Sep 19, 2023 pm 06:45 PM

在Windows11上的显示缩放方面,我们都有不同的偏好。有些人喜欢大图标,有些人喜欢小图标。但是,我们都同意拥有正确的缩放比例很重要。字体缩放不良或图像过度缩放可能是工作时真正的生产力杀手,因此您需要知道如何对其进行自定义以充分利用系统功能。自定义缩放的优点:对于难以阅读屏幕上的文本的人来说,这是一个有用的功能。它可以帮助您一次在屏幕上查看更多内容。您可以创建仅适用于某些监视器和应用程序的自定义扩展配置文件。可以帮助提高低端硬件的性能。它使您可以更好地控制屏幕上的内容。如何在Windows11

10种在 Windows 11 上调整亮度的方法10种在 Windows 11 上调整亮度的方法Dec 18, 2023 pm 02:21 PM

屏幕亮度是使用现代计算设备不可或缺的一部分,尤其是当您长时间注视屏幕时。它可以帮助您减轻眼睛疲劳,提高易读性,并轻松有效地查看内容。但是,根据您的设置,有时很难管理亮度,尤其是在具有新UI更改的Windows11上。如果您在调整亮度时遇到问题,以下是在Windows11上管理亮度的所有方法。如何在Windows11上更改亮度[10种方式解释]单显示器用户可以使用以下方法在Windows11上调整亮度。这包括使用单个显示器的台式机系统以及笔记本电脑。让我们开始吧。方法1:使用操作中心操作中心是访问

如何在Safari中关闭iPhone的隐私浏览身份验证?如何在Safari中关闭iPhone的隐私浏览身份验证?Nov 29, 2023 pm 11:21 PM

在iOS17中,Apple为其移动操作系统引入了几项新的隐私和安全功能,其中之一是能够要求对Safari中的隐私浏览选项卡进行二次身份验证。以下是它的工作原理以及如何将其关闭。在运行iOS17或iPadOS17的iPhone或iPad上,如果您在Safari浏览器中打开了任何“无痕浏览”标签页,然后退出会话或App,Apple的浏览器现在需要面容ID/触控ID认证或密码才能再次访问它们。换句话说,如果有人在解锁您的iPhone或iPad时拿到了它,他们仍然无法在不知道您的密码的情况下查看您的隐私

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
4 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

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.

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

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),

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment