Detailed explanation of cookies for PHP session control

小云云
Release: 2023-03-22 10:40:02
Original
1901 people have browsed it

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!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!