Introduction to cookie

Time:2020-2-18

Cookie is a piece of data that the server passes to the browser after the browser accesses the server.
Cookie is a part of HTTP protocol. When the client sends a request to the server for the first time, the server will send a cookie to the client to save some information. When the client sends a request to the same server next time, the server will make corresponding actions by identifying the cookie of the client. For example, when we log in to a website, this website records our user name and password. Next time we log in, we can log in directly without entering the user name and password.

The web server creates a cookie by sending a set cookie HTTP header, which is a string in the following format:

Set-Cookie: NAME=VALUE;Expires=DATE;Path=PATH;Domain=DOMAIN_NAME;SECURE

In the chrome console, we can view the HTTP message header sent to the browser after the server responds to the request through the developer tool to see the set cookie. The specific steps are as follows: F12 open the developer tool → network
Introduction to cookie

Also in the developer tool, you can view the cookies sent by the server through application:
Introduction to cookie

Name: the name of the cookie. Value is the value of the cookie set.

Expires: determine the effective expiration date of the cookie, specify when the cookie will not be sent to the server again, and the browser will delete the cookie after this specified time. The value of the date attribute must be in a specific format: WDY (day of week), date month year HH: mm: SS GMT. otherwise, it will not be recognized. When the expires option is not set, the lifetime of the cookie is limited to the current session, and closing the browser cookie file will automatically disappear.

Path: controls the sending time of the Cookie header. When the user requests the Path specified in the resource URL, the Web server will send the Cookie header. Generally, if the path part of the URL entered by the user contains the string defined by the path property from the first character, the browser will be deemed to pass the check. If the value of the path property is’ / ‘, all WWW resources on the web server can read the cookie. If the path option is not set, the property value of path defaults to the pathname of the resource that the web server passes to the browser.

Domain: determine which Internet domain web servers can read cookies accessed by browsers, that is, only pages from this domain can use the information in cookies. When the domain option is not set, the property value of the cookie is set to the domain name of the web server.

Note that the path attribute is only compared after the domain option has been verified.

Secure: only if the tag has no value, a cookie with the secure option can be sent to the server only when a request is created through SSL or HTTPS. Indicates that only when the communication protocol between the browser and the web server is encryption authentication protocol, the browser submits the corresponding cookie to the server.

In JavaScript, cookies are used to save state and provide an identity mechanism for web browsers. In JavaScript, we can create, maintain and delete cookies through the document. Cookie property.

Set cookie

document.cookie="userName = mavis ";

Each cookie is a name / value pair. To set multiple name / value pairs at one time, you can use the following methods:

document.cookie = "userName=mavis; userId = 023";

In cookies, the escape() function is used for encoding. It can express some special symbols in hexadecimal, such as semicolon (;), comma (,), equal sign (=), space, etc. However, after using escape() to encode, you need to use unescape() to decode after fetching the value to get the original cookie value.

The escape() function in JavaScript encodes a string so that it can be read on all computers. The syntax is as follows:escape(string), string is the string to be escaped or encoded.

Get the value of the cookie
Using the document.cookie, you can directly obtain a string of multiple name / value (name / value) separated by semicolons. These name / value pairs include all cookies under the domain name.

var myCookie = document.cookie;

Get the specified cookie value

//Set two cookies
    document.cookie = "userName=mavis";
    document.cookie = "userId = 023";
    //Get cookie string
    var myCookie = document.cookie;
    var arrCookie = myCookie.split(";");
    var userName;
    for(var i = 0;i < arrCookie.length;i++){
    var myArr = arrCookie[i].split("=");
    //Find the cookie with the name username and return a value
    if(userName = myArr[0]){
        userName = myArr[1];
        break;
        }
    }
    alert("welcome " + userName);

Set the effective end date of the cookie
When we log in to a website for the first time, some websites will remind us whether to save the ID and password. In JavaScript, we actually set a valid date for the cookie:

document.cookie = "userId = 023; expiress = GMT_String";

This statement sets the cookie userid to the expiration time indicated by GMT string. If it exceeds this time, the cookie will disappear and can no longer be accessed.
Set cookie value to expire after 30 days:

//Get current time 
    var date=new Date(); 
    var expiresDays=30; 
    //Set date to 30 days later 
    date.setTime(date.getTime()+expiresDays*24*3600*1000); 
    //Set the two cookies userid and username to expire in 30 days 
    document.cookie = "userId = 023; userName = mavis; expires = " + date.toGMTString();

delete cookie
You can set its effective end date to a time in the past:

var date=new Date(); 
//Set date to the past time
date.setTime(date.getTime()-10000); 
document.cookie="userId=023; expires="+date.toGMTString();

In this way, the cookie userid can be deleted.

Specify the path to the cookie: specified by setting the path property

//Specify the directory to access the cookie
document.cookie = "name = mavis; path = cookiePath"

//Accessible throughout the site
    document.cookie = "name = mavis; path = /"

Specifies the host name of the cookie that can be accessed: host name refers to different hosts in the same domain. Cookies created in one host cannot be accessed in another host, but can be controlled through the domain parameter.
Such as:document.cookie="name=value;domain=.baidu.com";This setting enables all hosts under Baidu to access the cookie.

An example:

function getCookie(name){
        if (document.cookie.length>0){
            start=document.cookie.indexOf(name + "=")
            if (start!=-1){ 
                start=start + name.length+1 
                end=document.cookie.indexOf(";",start)
                if (end==-1) end=document.cookie.length
                    return unescape(document.cookie.substring(start,end))
            } 
        }
        return ""
    }

    function setCookie(name,value,expiredays){
        var exdate=new Date()
        exdate.setDate(exdate.getDate()+expiredays)
        document.cookie=name+ "=" +escape(value)+((expiredays==null) ? "" : ";expires="+exdate.toGMTString())
    }
   Setcookie ("username", "tank", 1800); // set the value of cookie, and the lifetime is half an hour
   Alert (getcookie ('test ')); // get the value of cookie and display tank

However, there was a problem during the operation. It can’t be displayed on my Chrome browser:
Introduction to cookie

So I went online to check the following reasons, because Chrome browser has restrictions on cookies, but the cookie I gave Chrome browser has been set to “allow setting local data”, but it still can’t. Seeing this article, who can tell me why? be deeply grateful.

The following is displayed on the edge browser:
Introduction to cookie

Finally, the passing gods, please help to solve the problems that cannot be implemented on chrome, thank you~~~~

Recommended Today

Laravel service container must know

The article was forwarded from the professional laravel developer community. Original link: https://learnku.com/laravel/t To learn how to build an application with laravel is not only to learn how to use different classes and components in the framework, but also to remember allartisanCommand or all helper functions (we have Google). Learning to code with laravel is […]