search
HomeBackend DevelopmentPHP TutorialDetailed explanation of cookies for PHP session control

1. What is a cookie:

Sometimes also used in its plural form, Cookies refers to the data (usually encrypted) stored on the user's local terminal by some websites in order to identify the user's identity and perform session tracking. The most typical application of cookies is to determine whether a registered user has logged in to the website. The user may be prompted whether to retain user information the next time he enters the website to simplify the login procedure. These are the functions of cookies. Another important application is "shopping cart" processing. Users may choose different products on different pages of the same website within a period of time, and this information will be written to Cookies so that the information can be retrieved when making the final payment.

Advantages:

Good compatibility

Disadvantages:

1. Increased network traffic;

2. The data capacity is limited and can only store up to 4KB of data, which varies between browsers; the client can disable or clear cookies, thus affecting the functionality of the program.

3. It is unsafe. When multiple people share a computer, using cookies may leak user privacy and cause security issues.

2. Cookie working principle:

Cookie is a piece of text stored on the user's hard disk by the Web server, which stores some "key-value" pairs. Each Web site can store cookies on the user's machine and retrieve cookie data when needed. Usually Web sites have a cookie file. Every time the user visits site A, he will look for the cookie file of site A. If it exists, the username and password "key-value" pair data will be read from it. If the username and password "key-value" pair data is found, it is sent to site A together with the access request. If site A also receives the username and password "key-value" data when receiving the access request, it will use the username and password data to log in, so that the user does not need to enter the username and password. If the username and password "key-value" pair data is not received, it means that the user has not successfully logged in before. At this time, site A returns the login page to the user. In addition, each cookie has an expiration date, and cookies that have expired can no longer be used. Commonly used cookie operations are setting cookie data, reading cookie data, and deleting specified cookie data.

Syntax:

bool setcookie ( string $name [, string $value = "" [, int $expire = 0 [, string $path = "" [, string $domain = " " [, bool $secure = false [, bool $httponly = false ]]]]]] )

setcookie() defines the cookie and will be sent to the client together with the remaining HTTP headers . Like other HTTP headers, cookies must be sent before the script can produce any output (due to protocol limitations). Please call this function before producing any output (including and

or spaces). Once the cookie is set, it can be read using $_COOKIE the next time the page is opened. Cookie values ​​also exist in $_REQUEST

name: Cookie name.

value: Cookie value. This value is stored on the user's computer. Do not store sensitive information. For example, name is ‘cookiename’, and its value can be obtained through $_COOKIE[‘cookiename’].

expire: Cookie expiration time. This is a Unix timestamp, the number of seconds since the Unix epoch (January 1, 1970 00:00:00 GMT). In other words, you can basically use the result of the time() function plus the number of seconds you want to expire. Or you can use mktime(). time()+60*60*24*30 is to set the cookie to expire after 30 days. If set to zero, or if the parameter is omitted, the cookie will expire at the end of the session (i.e. when the browser is closed).

path: Cookie valid server path. When set to ‘/’, the cookie is valid for the entire domain name. If set to ‘/foo/’, the cookie is only valid for the /foo/ directory and its subdirectories in the domain (such as /foo/bar/). The default value is the current directory when the cookie is set.

domain: Valid domain name/subdomain name of the cookie. Setting it to a subdomain (e.g. ‘www.example.com’) will make the cookie valid for this subdomain and its third-level domain (e.g. w2.www.example.com). To make a cookie valid for an entire domain (including all its subdomains), just set it to the domain name (in this case, ‘example.com’).

secure: Set whether this cookie is only passed to the client through secure HTTPS connections. When set to TRUE, the cookie will only be set if a secure connection exists. If this requirement is handled on the server side, programmers need to only send such cookies over secure connections (as determined by $_SERVER["HTTPS"]).

httponly: Set to TRUE, the cookie can only be accessed through the HTTP protocol. This means that cookies cannot be accessed through scripting languages ​​​​such as JavaScript. FALSE, there is no limit.

Return value

If output is generated before calling this function, setcookie() will fail and return FALSE. Returns TRUE if setcookie() runs successfully. Of course, it does not mean whether the user has accepted cookies.

Setting and reading cookies

<?php
    $value="my cookie value"; //发送一个简单的cookie
    setcookie("testcookie",$value,time()+60);  //set cookie?><!DOCTYPE html><html><head>
    <meta charset="UTF-8">
    <title>Testcookie</title></head><body>
    <?php 
        if(isset($_COOKIE["testcookie"])) //判断是否存在
            echo($_COOKIE["testcookie"]."<br>");
        print_r($_COOKIE);    ?></body></html>

Deleting cookies

To delete a cookie, the expiration time should be set to the past to trigger the browser's deletion mechanism.

?>

用于记录当前用户访问网站的次数:

<?php

   if(isset($_COOKIE["num"]))        $num=$_COOKIE["num"];    else
       $num=0;                        //首次设置cookie

       $num=$num+1;                 
   setcookie("num",$num,time()+60*60) //发送一个cookie num记录访问次数?><!DOCTYPE html><html><head>
   <meta charset="UTF-8">
   <title>Testcookie</title></head><body>
   <?php 
       if($num>1)            echo("您已经第".$num."次访问本站点了。");        else
           echo("欢迎首次访问本站");        //关闭网页后,变量$num将被释放,但因为它的值已经保存再cookie中,所以下次打开网页会连续计数
   ?></body></html>

用户验证身份是验证cookie:

<?php  //身份验证cookie
   header("content-type:text/html;charset=utf-8");
   error_reporting(0);    //取输入的用户名和密码
       $uid=$_POST[&#39;username&#39;];        $upwd=$_POST[&#39;pwd&#39;];    //验证用户名和密码
   if($uid=="admin" && $upwd=="pass")
   {        echo("您已经登入成功,欢迎光临");        if($_POST[&#39;checkboxCookie&#39;]=="on")
       {
           setcookie("username",$uid,time()+60*60*24);
           setcookie("pwd",$upwd,time()+60*60*24);
       }
   }   
   else
       echo("登入失败,请返回重新登录");?><?php
   error_reporting(0);?><!DOCTYPE html><html><head>
   <meta charset="UTF-8">
   <title>Testcookie</title>
   <style type="text/css">form {    margin-top: 300px;    padding-left: 40%;}input[type="password"]{    margin-left: 16px;}input[type="reset"],input[type="submit"]{    margin-left: 80px;}</style></head><body>

   <form action="1.php" method="POST">

   <label>用户名:        <input type="text" name="uesrname" value=" <?php echo($_COOKIE["username"]);?>">    </label>
   <br><br>
                                                       <!-- 保留上次成功登入的用户名-->
   <lable>密码:    <input type="password" name="pwd" value="<?php echo($_COOKIE["password"]);?>" >    </lable>
                                                       <!-- 保留上次成功登入的用户名 -->
   <input type="checkbox" checked name="checkboxCookie">保留用户信息<br><br> <!-- 复选框 -->
   <input type="submit" name="put_info" value="登录">
   <input type="reset" name="rest_info" value="重置">
   </form></body></html>

相关推荐:

如何理解PHP中的会话控制

php中会话控制的深入理解

详细介绍php会话控制的实例代码

The above is the detailed content of Detailed explanation of cookies for PHP session control. For more information, please follow other related articles on the PHP Chinese website!

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
The Continued Use of PHP: Reasons for Its EnduranceThe Continued Use of PHP: Reasons for Its EnduranceApr 19, 2025 am 12:23 AM

What’s still popular is the ease of use, flexibility and a strong ecosystem. 1) Ease of use and simple syntax make it the first choice for beginners. 2) Closely integrated with web development, excellent interaction with HTTP requests and database. 3) The huge ecosystem provides a wealth of tools and libraries. 4) Active community and open source nature adapts them to new needs and technology trends.

PHP and Python: Exploring Their Similarities and DifferencesPHP and Python: Exploring Their Similarities and DifferencesApr 19, 2025 am 12:21 AM

PHP and Python are both high-level programming languages ​​that are widely used in web development, data processing and automation tasks. 1.PHP is often used to build dynamic websites and content management systems, while Python is often used to build web frameworks and data science. 2.PHP uses echo to output content, Python uses print. 3. Both support object-oriented programming, but the syntax and keywords are different. 4. PHP supports weak type conversion, while Python is more stringent. 5. PHP performance optimization includes using OPcache and asynchronous programming, while Python uses cProfile and asynchronous programming.

PHP and Python: Different Paradigms ExplainedPHP and Python: Different Paradigms ExplainedApr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

PHP and Python: A Deep Dive into Their HistoryPHP and Python: A Deep Dive into Their HistoryApr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

Choosing Between PHP and Python: A GuideChoosing Between PHP and Python: A GuideApr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP and Frameworks: Modernizing the LanguagePHP and Frameworks: Modernizing the LanguageApr 18, 2025 am 12:14 AM

PHP remains important in the modernization process because it supports a large number of websites and applications and adapts to development needs through frameworks. 1.PHP7 improves performance and introduces new features. 2. Modern frameworks such as Laravel, Symfony and CodeIgniter simplify development and improve code quality. 3. Performance optimization and best practices further improve application efficiency.

PHP's Impact: Web Development and BeyondPHP's Impact: Web Development and BeyondApr 18, 2025 am 12:10 AM

PHPhassignificantlyimpactedwebdevelopmentandextendsbeyondit.1)ItpowersmajorplatformslikeWordPressandexcelsindatabaseinteractions.2)PHP'sadaptabilityallowsittoscaleforlargeapplicationsusingframeworkslikeLaravel.3)Beyondweb,PHPisusedincommand-linescrip

How does PHP type hinting work, including scalar types, return types, union types, and nullable types?How does PHP type hinting work, including scalar types, return types, union types, and nullable types?Apr 17, 2025 am 12:25 AM

PHP type prompts to improve code quality and readability. 1) Scalar type tips: Since PHP7.0, basic data types are allowed to be specified in function parameters, such as int, float, etc. 2) Return type prompt: Ensure the consistency of the function return value type. 3) Union type prompt: Since PHP8.0, multiple types are allowed to be specified in function parameters or return values. 4) Nullable type prompt: Allows to include null values ​​and handle functions that may return null values.

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

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

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

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment