Home  >  Article  >  Backend Development  >  How to delete cookies in php

How to delete cookies in php

藏色散人
藏色散人Original
2020-11-05 11:19:082067browse

How to delete cookies in php: 1. Delete a single cookie through "setCookie("name","",time()-60); 2. Delete multiple cookies using foreach to traverse the array .

How to delete cookies in php

Recommended: "PHP Video Tutorial"

php Delete cookies

php A simple implementation method for batch deleting cookies

The code is as follows:

<?php
//删除单个cookie:键值设置为空、时间设置为过期了的时间
setCookie("name","",time()-60);
//删除多个cookie,采用遍历数组方式
foreach($_COOKIE as $key=>$value){
 setCookie($key,"",time()-60);
}
?>

Knowledge points: If all cookies of a website are deleted, the cookie file of the website is saved. will be deleted; if only one of the cookies is deleted, only the cookie information in the file will be deleted.

Use of PHP Cookie

1. Setting Cookie

PHP uses the SetCookie function to set Cookie. One thing that must be noted is that cookies are part of the HTTP protocol header and are used to transfer information between the browser and the server, so the Cookie function must be called before any content belonging to the HTML file itself is output.

The SetCookie function defines a Cookie and appends it to the end of the HTTP header. The prototype of the SetCookie function is as follows:

int SetCookie(string name, string value, int expire, string path, string domain, int secure);

All parameters except name are optional. The three parameters value, path, and domain can be replaced with empty strings, indicating that they are not set; the expire and secure parameters are numerical and can be represented by 0. The expire parameter is a standard Unix time stamp, which can be obtained using the time() or mktime() function, in seconds. The

secure parameter indicates whether this cookie is transmitted over the network through the encrypted HTTPS protocol.

The currently set cookie does not take effect immediately, but will not be visible until the next page. This is because the cookie is passed from the server to the client's browser in the set page, and the browser will not see it until the next page. The reason why the cookie can be removed from the client's machine and sent back to the server.

Setting cookies on the same page is actually from back to front, so if you want to delete a new cookie before inserting it, you must first write the insert statement and then write the delete statement, otherwise it may Undesirable results may occur.

Let’s look at a few examples:

Simple:

SetCookie("MyCookie", "Value of MyCookie");

With expiration time:

SetCookie("WithExpire", "Expire in 1 hour", time()+3600);//3600秒=1小时

Have everything:

SetCookie("FullCookie", "Full cookie value", time()+3600, "/forum", ".phpuser.com", 1);

There is another point to note here. For example, if your site has several different directories, then if you only use cookies without a path, the cookies set in a page in one directory will be used in a page in another directory. Invisible, that is to say, cookies are path-oriented. In fact, even if the path is not specified, the WEB server will automatically pass the current path to the browser, and specifying the path will force the server to use the set path. The way to solve this problem is to add the path and domain name when calling SetCookie. The format of the domain name can be "www.phpuser.com" or ". phpuser.com".

The part representing the value in the SetCookie function will be automatically encoded when passed. That is to say, if the value of the value is "test value", it will become "test value" when passed, which is the same as the URL. The method is the same. Of course, this is transparent to the program, because PHP automatically decodes the cookie value when it receives it.

If you want to set multiple cookies with the same name, use an array. The method is:

SetCookie("CookieArray[]", "Value 1");
SetCookie("CookieArray[]", "Value 2");

or

SetCookie("CookieArray[0]", "Value 1");
SetCookie("CookieArray[1]", "Value 2");

2. Receive and process Cookie

PHP The support for receiving and processing cookies is very good and is completely automatic. It is the same as the principle of FORM variables and is very simple.

For example, if you set a cookie named MyCookier, PHP will automatically analyze it from the HTTP header received by the WEB server and form a variable like an ordinary variable named $myCookie. The value of this variable It is the value of the cookie. The same applies to arrays. Another way is to reference PHP's global variable $HTTP_COOKIE_VARS array.

Examples are as follows: (assuming these have been set in previous pages and are still valid)

echo $MyCookie;
echo $CookieArray[0];
echo count($CookieArray);
echo $HTTP_COOKIE_VARS["MyCookie"];

It’s that simple.

3. Delete Cookie

To delete an existing Cookie, there are two ways:

First, call SetCookie with only the name parameter, then the name is this The cookie of name will be deleted from the related user computer;

Another way is to set the cookie expiration time to time() or time()-1, then the cookie will be deleted after the page is browsed. Deleted (actually invalidated).

It should be noted that when a Cookie is deleted, its value is still valid on the current page.

4. Restrictions on the use of Cookies

First of all, it must be set before the content of the HTML file is output;

Secondly, different browsers handle Cookies inconsistently, and sometimes Incorrect results will occur. For example: MS IE SERVICE PACK 1 cannot correctly handle Cookies with domain name and path, Netscape Communicator 4.05 and MS IE 3.0 cannot correctly handle Cookies without path and time. As for MS IE 5, it seems that it cannot handle cookies with domain name, path and time. This is something I discovered while designing the pages of this site.

The third limitation is on the client side.

The maximum number of cookies that a browser can create is 30, and each cannot exceed 4KB. The total number of cookies that can be set by each WEB site cannot exceed 20.

PHP DELETE COOKIE METHOD

首先我们看一下php手册中关于删除cookie的说明

------以下引用php手册内容--------------

bool setcookie ( string name [, string value [, int expire [, string path [, string domain [, bool secure]]]]] )

要删除 cookie 需要确保它的失效期是在过去,才能触发浏览器的删除机制。

下面的例子说明了如何删除刚才设置的 cookie: 例子 2. setcookie() 删除

例子

// 将过期时间设为一小时前
setcookie("TestCookie", "", time() - 3600);
setcookie("TestCookie", "", time() - 3600, "/~rasmus/", ".utoronto.ca", 1);
----------------引用结束--------------------------

删除一个cookie的方法就是把这个cookie的有效期设置为当前时间以前,这

也是几乎所有php程序员都会这么做。

后来一个初接触php的朋友告诉我,他在程序中本想把一个cookie的值设置为空,结果导致这个cookie直接被删除。我当时的第一反应是不相信,于是测试了一下

setcookie("testcookie", &#39;&#39;);
print_r($_COOKIE);

结果果然是整个$_COOKIE数组都是空的,而非仅仅$_COOKIE['testcookie']为空.于是用winsock抓包,观察返回的http头,发现http头竟然是

Set-Cookie: testcookie=deleted; expires=Mon, 18-Jun-2007 02:42:33 GMT

这说明setcookie("testcookie", '');的的确确是将testcookie这个cookie直接删除.而关于这种情况在php手册中完全没有说明.

最后阅读php源码,终于发现真相(这就是开源的好处了,有什么不清楚的内幕直接查源码)

以下代码可以在php5.20的Linux源码包中ext/standard/head.c第99行附近找到.

if (value && value_len == 0) {
/*
    * MSIE doesn&#39;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);
}
}

源码中清清楚楚的显示,if (value && value_len == 0) ,当value_len为0时

sprintf(cookie, "Set-Cookie: %s=deleted; expires=%s", name, dt);

会发送删除cookie的http头给浏览器.

最后我们可以得出结论,在php中使用

setcookie($cookiename, &#39;&#39;);或者 setcookie($cookiename, NULL);

都会删除cookie,当然这些手册中并没有。

The above is the detailed content of How to delete cookies in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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