This article mainly shares with you the detailed explanation of how to delete cookie instances in PHP. Let's first look at the mechanism of related cookies, hoping to help everyone.
bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, bool secure]]]]] )
To delete a cookie, you need to ensure that its expiration date is in the past to trigger the browser's deletion mechanism.
The following example illustrates how to delete the cookie just set:
//将过期时间设为一小时前setcookie("TestCookie", "", time() - 3600); setcookie("TestCookie", "", time() - 3600, "/~rasmus/", ".utoronto.ca", 1); ?>
The way to delete a cookie is to set the validity period of the cookie to before the current time. This is also the case for almost all cookies. All PHP programmers do this.
Later, a friend who was new to PHP told me that he wanted to set the value of a cookie to empty in the program, but the cookie was deleted directly. My first reaction at the time was that I didn't believe it, so I tested it:
setcookie("testcookie", ''); print_r($_COOKIE);
if (value && value_len == 0) { /* * MSIE doesn't delete a cookie when you set it to a null value * so in order to force cookies to be deleted, even on MSIE, we * pick an expiry date 1 year and 1 second in the past */ time_t t = time(NULL) - 31536001; dt = php_format_date("D, d-M-Y H:i:s T", sizeof("D, d-M-Y H:i:s T")-1, t, 0 TSRMLS_CC); sprintf(cookie, "Set-Cookie: %s=deleted; expires=%s", name, dt); efree(dt); } else { sprintf(cookie, "Set-Cookie: %s=%s", name, value ? encoded_value : ""); if (expires > 0) { strcat(cookie, "; expires="); dt = php_format_date("D, d-M-Y H:i:s T", sizeof("D, d-M-Y H:i:s T")-1, expires, 0 TSRMLS_CC); strcat(cookie, dt); efree(dt); } }
Detailed explanation of getting cookies and deleting cookies using JavaScript
php cookie class (set, get, delete cookie value)
The above is the detailed content of Detailed explanation of how to delete cookie instances in php. For more information, please follow other related articles on the PHP Chinese website!