Home > Article > Backend Development > How to set cookie scope in php?
In PHP, you can use the setcookie() function to set the scope of the cookie. The syntax is "setcookie(name, value, expire, path, domain, secure)". You can set the cookie scope by setting the value of the domain parameter,
When we set cookies for the website, did you find that these cookies were also received under other domain names of the website? These useless cookies may not seem to account for much traffic, but for a site with tens of millions of PV per day, the wasted resources are not a small amount. Therefore, when setting a cookie, its scope must be set accurately.
We all know that setcookie is used in PHP to set the cookie of the website. [Recommended related tutorials: "PHP Tutorial"]
The usage of this function is as follows :
setcookie(name,value,expire,path,domain,secure)
Today we will discuss its fifth parameter domain, because it determines the scope of the cookie.
Now there are the following 3 domain names, a top-level domain name, a second-level domain name and a third-level domain name:
① zydya.com
②blog.zyday.com
③one.blog.zyday.com
First set cookies under the domain name ①zyday.com, do four tests, and set the domain parameters to empty and 'zyday.com' , 'blog.zyday.com' and 'one.blog.zyday.com'.
√ indicates that the cookie can be obtained under the domain name, × indicates that the cookie cannot be obtained
domain parameter | zydya.com | blog.zyday.com | one.blog.zyday.com |
setcookie('name',1,time() 1) | √ | ## √ | ## √|
√ | √ | √ | ##setcookie('name',1,time() |
× |
× | × | ##setcookie('name',1,time() | 1,'/','one.blog.zyday.com')
× |
× | ##× | When domain is set to empty, domain defaults to the current domain name, and subdomains under this domain name can receive cookies. |
##one.blog.zyday.com | setcookie('name',1,time() 1) | × | |||||||||||||||||||
√ |
√ | ##setcookie('name',1,time() 1,'/','zyday.com') | √ | ||||||||||||||||||
##√ | setcookie( 'name',1,time() 1,'/','blog.zyday.com') | ×√ | |||||||||||||||||||
√ | setcookie('name',1,time() 1,'/',one.blog.zyday.com') | ×##× | |||||||||||||||||||
Look at the second line. The domain parameter is zyday.com, which is the parent domain name of blog.zyday.com. Then all subdomain names under zyday.com (including zyday.com, blog.zyday.com, one.blog.zyday .com) can receive cookies. When the domain is its own domain name, its parent domain name is not affected, and it and its subdomain names can receive cookies.
Recommended learning: PHP programming from entry to proficiency |
The above is the detailed content of How to set cookie scope in php?. For more information, please follow other related articles on the PHP Chinese website!