Home >Backend Development >PHP Tutorial >PHP cookie clearing and cookies cannot be deleted under ff_PHP tutorial
We use setcookie to set and delete cookies in php, and they will be automatically deleted when they expire. However, under ff, you may encounter cookies that cannot expire.
First, let’s take a look at the instructions on deleting cookies in the PHP manual
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: Example 2. setcookie() delete
Example
The code is as follows | Copy code | ||||||||
setcookie("TestCookie", "", time() - 3600);
|
The code is as follows | Copy code |
setcookie("username", "", time()-3600);
|
Exit and test under IE without any problems. Since you are building a website, you must be compatible with as many browsers as possible, haha. So I tested it in Firefox and everything worked fine when logging in. But when I launched it, I ran into trouble. There is no way to log out, the user is always logged in. So I checked the difference between cookie records in IE and Firefox, and after testing, I suddenly realized it.
It turns out that if the fourth parameter (legal path parameter) of setcookie() is not specified, the current directory will be used as the legal path by default, and the path I tested is: http://127.0.0.1/php/rss2fla/data /log.php, so the cookie paths set when logging in and logging out are different.
IE is more user-friendly than Firefox. Haha, when specifying the path, it will overwrite the cookie variable with the same name under the current IP. However, FireFox is more strict, resulting in a new variable...
代码如下 | 复制代码 |
SetCookie("MyCookie", "Value of MyCookie"); |
代码如下 | 复制代码 |
SetCookie("WithExpire", "Expire in 1 hour", time()+3600);//3600秒=1小时 |
The code is as follows | Copy code | ||||
SetCookie("MyCookie", "Value of MyCookie");
|
The code is as follows | Copy code |
SetCookie("WithExpire", "Expire in 1 hour", time()+3600);//3600 seconds=1 hour |
The code is as follows | Copy code |
SetCookie("FullCookie", "Full cookie value", time()+3600, "/forum", ".bKjia.c0m", 1); |
The last one is compatible with all browsers.
To sum up, it is best to use the following method when operating cookies in php:
代码如下 | 复制代码 |
if(isset($_COOKIE["sid"]) && !empty($_COOKIE["sid"])){ // 这样可以保证Cookie存在且在有效期内 …… } |