Home >Backend Development >PHP Tutorial >When php setcookie the value is null or empty string (delete cookie)_PHP tutorial
Setting cookies and deleting cookies in php can be achieved using php setcookie. If it is set, it will be set with a value. If it is deleted, it will be set. The cookie value can be deleted if it is empty or null or the time has expired. Let's look at some examples below.
For a long time, when deleting cookies in php, you have used
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string
$domain [, bool $secure = false [, bool $httponly = false ]]]]]] )
Write $value as you like, and set $expire to a time that has passed.
This is also written in the official documentation:
http://www.php.net/manual/en/function.setcookie.php
Example #2 setcookie() delete example
When deleting a cookie you should assure that the expiration date is in the past, to trigger
the removal mechanism in your browser. Examples follow how to delete cookies sent in previous
example:
The code is as follows | Copy code |
代码如下 | 复制代码 |
// set the expiration date to one hour ago setcookie ("TestCookie", "", time() - 3600); setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", "example.com", 1); ?> |
setcookie ("TestCookie", "", time() - 3600);
setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", "example.com", 1);?>
I encountered a strange thing today. When setting cookie, I passed an empty string to $value, but the result turned out to be that the cookie was deleted代码如下 | 复制代码 |
$name = "post_url"; delete_cookie |
The code is as follows | Copy code |
$name = "post_url"; $value = ""; setcookie($name, $value, time()+60*60*3, "/" ); delete_cookie |
Quite puzzled.
Go to the source code of php 5.4.13:
ext/standard/head.c
The code is as follows | Copy code |
173 PHP_FUNCTION(setcookie) FAILURE) { domain_len, secure, 1, httponly TSRMLS_CC) == SUCCESS) { expires, char *path, int path_len, char *domain, int domain_len, int secure, int url_encode, int httponly TSRMLS_DC) and 14 */ trn
86 return FAILURE;
90 zend_error( E_WARNING, "Cookie values cannot contain any of the following ',; trn |