Home Backend Development PHP Tutorial Detailed explanation of cookies for PHP session control

Detailed explanation of cookies for PHP session control

Mar 26, 2018 pm 02:24 PM
cookie ie php

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>
Copy after login

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>
Copy after login

用户验证身份是验证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>
Copy after login

相关推荐:

如何理解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 of this Website
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

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

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles