Cookie Brief Explanation

The meaning of cookies

  • Suppose that after I log in, a piece of information is saved in my cookie. The expiration time of this information is 7 days.
    • No matter if I close the browser or not, as long as I don’t clear the cache, the cookie will always be there.
    • Expires in 7 days
  • When I log in:
    • Let me first check if there is any information I saved in the cookie
    • If there is, then directly follow the login to complete the processing
    • If not, it will be handled as not logged in
  • As long as I log in once:
    • This login information can be saved within 7 days
    • There is no need to log in again within 7 days, every time you open the website, it will be processed according to the login completion.
    • After 7 days, you need to log in again
    • That is to realize the 7-day login-free function

What is a cookie

  • cookieIs a location where data is stored in the form of a string
  • Every HTTP request will carry the cookie in the request header to the server
  • Every HTTP response will carry a cookie in the response header to the client
  • In other words, the cookie does not need to be manually set by us, it will automatically move data between the client and the server
  • We just need to set the content of the cookie.

Storage form of cookie

  • The cookie is stored in key=valuethe form of a string and appears in the string in the form of
  • Each key=valueis a piece of data
  • ;Split between multiple data
// cookie的形态
`a=100; b=200; c=300;`

Characteristics of cookies

  • Stored by domain name: that is, whoever sets it can read it
  • Timeliness: that is, there is an expiration time,
    1. The default is the session level (that is, it expires when the browser is closed)
    2. Can be set manually
  • Storage size is limited: generally 4kb or about 50
  • Both front and back ends can be operated:
    1. Front-end operation through js
    2. The backend operates through the backend language
  • Request automatic carry:
    1. When there is content in your cookie space
    2. As long as it is any request under the current domain name, it will automatically carry the cookie and put it in the request header
    3. How much is automatically carried in the cookie
    4. If there is no content in the cookie, it will not be carried

JS operation cookie

Add cookie

  • grammar:document.cookie = "key=value";
  • Note: You can only set one cookie at a time, if you want to set two, you have to write twice
  • Timeliness of setting cookies
    • When not set, the default is session aging (disappear after closing the browser)
    • Setting the timeliness of the cookie is to modify the cookie
      • document.cookie = "key=value; 修饰信息1=修饰的值1;修饰信息2=修饰的值2"
      • Set expiration time:document.cookie = "key=value; expires = 时间对象"
      • Set a valid path: document.cookie = "key=value; path=路径"(If path is not set, the default is the current directory path)
  • Timing of setting cookies
    • What we get using new Date() is the time of our terminal, which is the time in the +8 time zone
    • Suppose we get 9:30 with new Date()
    • But the time of this cookie in our terminal is 17::30
    • If you want the cookie to expire at the current time
    • Then the terminal time you get is -8 hours
// 增加一条cookie
document.cookie = 'a=100';

// 再增加一条cookie
document.cookie = 'b=hello';

// 设置有过期时间的cookie
var date = new Date('2022/2/12');
document.cookie = "c=200; expires="+date;

// 设置cookie的path
document.cookie = "d=300;path=/";

// 设置一个cookie在5秒后过期
var date1 = new Date();
// 把当前时间往前推8个小时消失,在增加5秒时间
date1.setTime(date1.getTime()-8*60*60*1000+5*1000);
document.cookie = "e=200;expires="+date1;

// 设置一个有过期时间的cookie
document.cookie = 'f=100; expires=Thu,18 Dec 2043 12:00:00 GMT';// 上面这个 cookie 数据会在 2043 年 12 月 18 日 12 点以后过期,过期后会自动消失

// 获取cookie
console.log(document.cookie);

Delete cookie

  • Cookies cannot be deleted
  • If you don't want this cookie anymore
  • Then set the expiration time of this cookie to before the current time, then delete
// 先设置一条cookie
document.cookie = "name=zhangsan";
// 在删除这条cookie
var date = new Date();
date.setTime(date.getTime()-8*60*60*1000-1);
document.cookie = "name=zhangsan;path=/;expires="+date;

Get cookie

  • js gets the cookie:document.cookie
  • He can't get a single piece of data, he can only get all cookies
document.cookie = "aa=100";
document.cookie = "bbb=200";
document.cookie = "c=300";
document.cookie = "ac=60";
console.log(document.cookie);

var key = "ac";
var result;	//结果保存在这个变量里面
var str = document.cookie;	//"a=500; aa=100; bbb=200; c=300; ac=60"

//先把字符串以“; ”为分隔符,变成一个数组:['a=500','aa=100','bbb=200','c=300','ac=60']
var arr = str.split("; ");

// 遍历数组arr,看数组里面每一项
for(var i=0; i<arr.length; i++){
    
    
	// arr[0] = "a=500"
	// 把arr[i]以=为分隔符,前面是key,后面是value
	var tempArr = arr[i].split("=");//['a','500']
	if(tempArr[0]==key){
    
    
		// 如果这一项=前面的内容和key相同,=后面的值就是我们要的值,循环结束
		result = tempArr[1];
		break;
	}
	// 如果这一项的=前面的内容和key不相同,=后面的值就不是我们要的值,继续下一次
}
console.log(result);

JS operation cookie package

  • Because there is no special method for adding, deleting, checking and modifying cookies in js
  • So we need to encapsulate a method ourselves

Set cookie

/**
 * setCookie 用于设置 cookie
 * @param {STRING} key  要设置的 cookie 名称
 * @param {STRING} value  要设置的 cookie 内容
 * @param {NUMBER} expires  过期时间
 */
function setCookie(key, value, expires){
    
    
	const time = new Date();
	time.setTime(time.getTime()-1000*60*60*24*8+expires);
	document.cookie = `${
      
      key}= ${
      
      value}; expires=${
      
      time}`;
}

Delete cookie

/**
 * delCookie 删除 cookie 中的某一个属性
 * @param {STRING} name 你要删除的某一个 cookie 属性的名称
 */
function delCookie(name){
    
    
	setCookie(name,1,-1);
}

Get cookie

/**
 * getCookie 获取 cookie 中的某一个属性
 * @param {STRING} key 你要查询的 cookie 属性
 * @return {STRING} 你要查询的那个 cookie 属性的值
 */
function getCookie(key){
    
    
	const cookieArr = document.cookie.split('; ');//这里 ; 号后面有个空格不能漏
	let value = '';
	cookieArr.forEach(item=>{
    
    
		if(item.split('=')[0] === key){
    
    
			value = item.split('=')[1];
		}
	})
	return value;
}

PHP manipulation cookie

Add cookie

  • grammar:setcookie(key,value,过期时间);
    • key: the name of the cookie to be set
    • value: the value of the cookie to be set
    • Expiration time: You can not write, the default is the session time limit
  • The backend obtains the time object using the time() method
    • What you get is the world standard time in seconds
    • 15 seconds after the current time: time()+15
    • setcookie('php','200',time()+15);

Modify cookie

  • Backend modify cookie
    • Also use the setcookie method
    • Just set it up again
    • setcookie('a',100);
    • setcookie('a',200);

Delete cookie

  • Delete cookies on the backend
    • Also use the setcookie method
    • It’s just that the cookie’s expiration time is set to before the current time
    • setcookie('a','hello',time()-1);

Get cookie

  • Get cookies from the backend
    • When the front end sends a request, the cookie will be carried in the request header
    • PHP has a predefined variable called$_COOKIE
    • Is an associative array, similar to$_GET/$_POST
    • Stored in it is cookie information one by one
    • Which one you want, just $_COOKIEtake it out

Code demo

<?php
// 设置cookie,15秒后过期
setcookie('php',200,time()+15);

// 修改cookie,过期时间不写相当于改回默认过期时间
setcookie('php',100);

// 获取cookie
$php = $_COOKIE['php']; //$php=100

// 删除cookie
setcookie('php',100,time()-1);
?>

Guess you like

Origin blog.csdn.net/qq_45677671/article/details/113946466