In PHP, you can use the setcookie() function to delete cookies. You only need to set the second parameter of the function to empty, or set the third parameter to be less than the current time of the system.
The operating environment of this tutorial: windows7 system, PHP7.1 version, DELL G3 computer
When the cookie is created, if it is not set expiration time, the cookie file will be automatically deleted when the browser is closed. If you want to delete the cookie file before closing the browser, you need to use the setcookie() function.
There are two ways to delete cookies using the setcookie() function. Let me give you a detailed introduction below.
Method 1: Use the setcookie() function to set the Cookie value (that is, the second parameter) to empty
<?php echo '<pre class="brush:php;toolbar:false">'; if(!isset($_COOKIE['url']) && !isset($_COOKIE['name'])){ setcookie('url','https://www.php.cn/'); setcookie('name','PHP中文网'); echo '首次运行,设置 url、name 两个 Cookie 的值'; }else if(isset($_COOKIE['url'])){ echo '查看 Cookie 的值,如下所示:<br>'; print_r($_COOKIE); echo '清除 url 的值'; setcookie('url',''); }else{ print_r($_COOKIE); } ?>
Run the above code for the first time Two cookies named url and name will be created; run it again to view the value of the cookie and clear the value of url; run it a third time to view the cleared results. As shown below:
// 第一次运行 首次运行,设置 url、name 两个 Cookie 的值 // 第二次运行 查看 Cookie 的值,如下所示: Array ( [url] => https://www.php.cn/ [name] => PHP中文网 ) 清除 url 的值 // 第三次运行 Array ( [name] => PHP中文网 )
Method 2: Use the setcookie() function to set the Cookie expiration time (that is, the third parameter) to be less than the current time of the system.
<?php echo '<pre class="brush:php;toolbar:false">'; if(!isset($_COOKIE['url']) && !isset($_COOKIE['name'])){ setcookie('url','https://www.php.cn/'); setcookie('name','PHP中文网'); echo '首次运行,设置 url、name 两个 Cookie 的值'; }else if(isset($_COOKIE['url'])){ echo '查看 Cookie 的值,如下所示:<br>'; print_r($_COOKIE); echo '清除 url 的值'; setcookie('url','https://www.php.cn/', time()-1); }else{ print_r($_COOKIE); } ?>
The running results are as follows:
// 第一次运行 首次运行,设置 url、name 两个 Cookie 的值 // 第二次运行 查看 Cookie 的值,如下所示: Array ( [url] => https://www.php.cn/ [name] => PHP中文网 ) 清除 url 的值 // 第三次运行 Array ( [name] => PHP中文网 )
Recommended learning: "PHP Video Tutorial"
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!