Home php教程 php手册 php setcookie时值为null或空字符串(删除cookie)

php setcookie时值为null或空字符串(删除cookie)

Jun 13, 2016 am 09:51 AM
cookie null php setcookie for delete exist string set up

在php中设置cookie与删除cookie都可以使用php setcookie来实现,如果设置就设置有值,如果删除就设置 cookie value为空或null或时间过期都可以删除,下面我们来看一些实例。

长久以来,在php中删除cookie的时候,都是使用
bool setcookie ( string $name [, string $value [, int $expire = 0 [, string $path [, string

$domain [, bool $secure = false [, bool $httponly = false ]]]]]] )

$value 随便写, $expire设置为一个已经过去的时间即可。

官方文档中也是这样写的:

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:

 代码如下 复制代码
// set the expiration date to one hour ago
setcookie ("TestCookie", "", time() - 3600);
setcookie ("TestCookie", "", time() - 3600, "/~rasmus/", "example.com", 1);
?>

今天遇到一件奇怪的事, 在setcookie的时候,传了一个空字符串给$value,结果竟然是此cookie被删除了

 代码如下 复制代码

$name = "post_url";
$value =  "";
setcookie($name, $value,  time()+60*60*3, "/" );

delete_cookie

相当不解。

去翻php 5.4.13 的源码:

ext/standard/head.c

 代码如下 复制代码

173 PHP_FUNCTION(setcookie)
174 {
175     char *name, *value = NULL, *path = NULL, *domain = NULL;
176     long expires = 0;
177     zend_bool secure = 0, httponly = 0;
178     int name_len, value_len = 0, path_len = 0, domain_len = 0;
179
180     if (zend_parse_parameters(ZEND_NUM_ARGS() TSRMLS_CC, "s|slssbb", &name,
181                               &name_len, &value, &value_len, &expires, &path,
182                               &path_len, &domain, &domain_len, &secure, &httponly) ==

FAILURE) {
183         return;
184     }
185
186     if (php_setcookie(name, name_len, value, value_len, expires, path, path_len, domain,

domain_len, secure, 1, httponly TSRMLS_CC) == SUCCESS) {
187         RETVAL_TRUE;
188     } else {
189         RETVAL_FALSE;
190     }  
191 }      
 
 
 
 76 PHPAPI int php_setcookie(char *name, int name_len, char *value, int value_len, time_t

expires, char *path, int path_len, char *domain, int domain_len, int secure, int url_encode,

int httponly TSRMLS_DC)
 77 {
 78     char *cookie, *encoded_value = NULL;
 79     int len=sizeof("Set-Cookie: ");
 80     char *dt;
 81     sapi_header_line ctr = {0};
 82     int result;
 83
 84     if (name && strpbrk(name, "=,; trn1314") != NULL) {   /* man isspace for 13

and 14 */
 85         zend_error( E_WARNING, "Cookie names cannot contain any of the following '=,;

\t\r\n\013\014'" );
 86         return FAILURE;
 87     }
 88
 89     if (!url_encode && value && strpbrk(value, ",; trn1314") != NULL) { /* man

isspace for 13 and 14 */
 90         zend_error( E_WARNING, "Cookie values cannot contain any of the following ',;

\t\r\n\013\014'" );
 91         return FAILURE;
 92     }
 93
 94     len += name_len;
 95     if (value && url_encode) {
 96         int encoded_value_len;
 97
 98         encoded_value = php_url_encode(value, value_len, &encoded_value_len);
 99         len += encoded_value_len;
100     } else if ( value ) {
101         encoded_value = estrdup(value);
102         len += value_len;
103     }
104     if (path) {
105         len += path_len;
106     }
107     if (domain) {
108         len += domain_len;
109     }
110
111     cookie = emalloc(len + 100);
112
113     if (value && value_len == 0) {
114         /*
115          * MSIE doesn't delete a cookie when you set it to a null value
116          * so in order to force cookies to be deleted, even on MSIE, we
117          * pick an expiry date in the past
118          */
119         dt = php_format_date("D, d-M-Y H:i:s T", sizeof("D, d-M-Y H:i:s T")-1, 1, 0

TSRMLS_CC);
120         snprintf(cookie, len + 100, "Set-Cookie: %s=deleted; expires=%s", name, dt);
121         efree(dt);
122     } else {
123         snprintf(cookie, len + 100, "Set-Cookie: %s=%s", name, value ? encoded_value :

"");
124         if (expires > 0) {
125             const char *p;
126             strlcat(cookie, "; expires=", len + 100);
127             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);
128             /* check to make sure that the year does not exceed 4 digits in length */
129             p = zend_memrchr(dt, '-', strlen(dt));
130             if (!p || *(p + 5) != ' ') {

参数中的value在C语言中的类型是char * , 还有一个 value_len标明了它的长度。
如果value_len为0的话,就写了下面的cookie:
值为”deleted”, 过期时间为 Thu, 01-Jan-1970 08:00:01 CST 或者说是 Thu, 01-Jan-1970 00:00:01

GMT

看来setcookie($name, “”) 确实可以删除这个cookie了…
同理,在php中,strval(NULL) === “” , 所以 setcookie($name, NULL) 也就相当于 setcookie($name,

“”),同样可以删除此cookie.

另外,比较好奇的是:

 代码如下 复制代码
if (value && value_len == 0) {
}
else {
}

else 中包含了 value 为null 的情况, 这是一种什么样的情况呢?

看来setcookie($name, “”) 确实可以删除这个cookie了…
同理,在php中,strval(NULL) === “” , 所以 setcookie($name, NULL) 也就相当于 setcookie($name,

“”),同样可以删除此cookie.

另外,比较好奇的是:

 代码如下 复制代码
if (value && value_len == 0) {
}
else {
}

else 中包含了 value 为null 的情况, 这是一种什么样的情况呢?

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian PHP 8.4 Installation and Upgrade guide for Ubuntu and Debian Dec 24, 2024 pm 04:42 PM

PHP 8.4 brings several new features, security improvements, and performance improvements with healthy amounts of feature deprecations and removals. This guide explains how to install PHP 8.4 or upgrade to PHP 8.4 on Ubuntu, Debian, or their derivati

How To Set Up Visual Studio Code (VS Code) for PHP Development How To Set Up Visual Studio Code (VS Code) for PHP Development Dec 20, 2024 am 11:31 AM

Visual Studio Code, also known as VS Code, is a free source code editor — or integrated development environment (IDE) — available for all major operating systems. With a large collection of extensions for many programming languages, VS Code can be c

Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Explain JSON Web Tokens (JWT) and their use case in PHP APIs. Apr 05, 2025 am 12:04 AM

JWT is an open standard based on JSON, used to securely transmit information between parties, mainly for identity authentication and information exchange. 1. JWT consists of three parts: Header, Payload and Signature. 2. The working principle of JWT includes three steps: generating JWT, verifying JWT and parsing Payload. 3. When using JWT for authentication in PHP, JWT can be generated and verified, and user role and permission information can be included in advanced usage. 4. Common errors include signature verification failure, token expiration, and payload oversized. Debugging skills include using debugging tools and logging. 5. Performance optimization and best practices include using appropriate signature algorithms, setting validity periods reasonably,

How do you parse and process HTML/XML in PHP? How do you parse and process HTML/XML in PHP? Feb 07, 2025 am 11:57 AM

This tutorial demonstrates how to efficiently process XML documents using PHP. XML (eXtensible Markup Language) is a versatile text-based markup language designed for both human readability and machine parsing. It's commonly used for data storage an

Explain late static binding in PHP (static::). Explain late static binding in PHP (static::). Apr 03, 2025 am 12:04 AM

Static binding (static::) implements late static binding (LSB) in PHP, allowing calling classes to be referenced in static contexts rather than defining classes. 1) The parsing process is performed at runtime, 2) Look up the call class in the inheritance relationship, 3) It may bring performance overhead.

PHP Program to Count Vowels in a String PHP Program to Count Vowels in a String Feb 07, 2025 pm 12:12 PM

A string is a sequence of characters, including letters, numbers, and symbols. This tutorial will learn how to calculate the number of vowels in a given string in PHP using different methods. The vowels in English are a, e, i, o, u, and they can be uppercase or lowercase. What is a vowel? Vowels are alphabetic characters that represent a specific pronunciation. There are five vowels in English, including uppercase and lowercase: a, e, i, o, u Example 1 Input: String = "Tutorialspoint" Output: 6 explain The vowels in the string "Tutorialspoint" are u, o, i, a, o, i. There are 6 yuan in total

What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? What are PHP magic methods (__construct, __destruct, __call, __get, __set, etc.) and provide use cases? Apr 03, 2025 am 12:03 AM

What are the magic methods of PHP? PHP's magic methods include: 1.\_\_construct, used to initialize objects; 2.\_\_destruct, used to clean up resources; 3.\_\_call, handle non-existent method calls; 4.\_\_get, implement dynamic attribute access; 5.\_\_set, implement dynamic attribute settings. These methods are automatically called in certain situations, improving code flexibility and efficiency.

PHP and Python: Comparing Two Popular Programming Languages PHP and Python: Comparing Two Popular Programming Languages Apr 14, 2025 am 12:13 AM

PHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.

See all articles