Home > Article > Backend Development > How to set a cookie in php to be valid for the entire domain name?
php method to set a cookie to be valid for the entire domain name: use the setcookie function to make the cookie valid for the entire domain name, the code is [setcookie("cookie_test", 'this is cookie test', time() 3600,"/" ,"].
php method to set a cookie that is valid for the entire domain name:
The default cookie is only It is valid for the domain name (for example, www.php.com) itself. If the domain name (for example, test.php.com) is exceeded, the cookie will be invalid. However, the setcookie function can be used to make the cookie valid for the entire domain name (*.php.com). .
setcookie("cookie_test", 'this is cookie test', time()+3600, "/", "php.com");
Since the domain name related parameters are in the fifth, all the previous parameters need to be set. The first parameter is the cookie name, the second parameter is the cookie value, and the third parameter is the cookie expiration time. , these parameters are generally common parameters, and will not be introduced in detail here.
What needs to be emphasized here is the fourth parameter. This parameter is used to set the effective path of the cookie. If it is set to /
, it is valid for all directories. If it is set to /test/
, it is only valid for /test/
and its subdirectories /test/tmp/
is valid. Under normal circumstances, it will be set to /
, which is valid for the entire directory.
Then comes the fifth parameter, which is our protagonist today. The fifth parameter is It specifies the domain name for the cookie to be effective. Under normal circumstances, the cookie will only take effect under the current domain name. For example, the cookie under test.php.com will not take effect on www.php.com, but we can set it so that the cookie will be in the same main domain name. Under general use, you only need to set this parameter to the main domain name (www.php.com is also a subdomain name, don’t get confused).
Both the fourth parameter and the fifth parameter can control cookies. The effective range can be set according to the actual situation.
Related learning recommendations: PHP programming from entry to proficiency
The above is the detailed content of How to set a cookie in php to be valid for the entire domain name?. For more information, please follow other related articles on the PHP Chinese website!