Home > Article > Backend Development > How to use cookies in php?
This article mainly introduces how to use cookie in php, including creating/updatingcookie ,Deletecookie, get cookie value, etc. Friends who need it can refer to the following
1. Create/update cookie
The code is as follows:
setCookie($cookieName,$value,time()+秒数);
Example: Create a cookie with the name UserName, value zs, and expiration time of 2 weeks
The code is as follows:
setcookie("UserName","zs",time()+2*7*24*3600);
If the time is not set, it will not Save to cookie file. It can be accessed when the browser is not closed. When the browser is closed, it is no longer accessible.
Example:
The code is as follows:
setcookie("Age","18");
2. Get the value of cookie
The code is as follows:
$_cookie[$cookieName];
Example: Take out the value of UserName and put it in the variable $uName
The code is as follows:
$uName=$_COOKIE['UserName'];
When taking the value, it will usually be judged first whether is empty, then perform the value operation. The above value operation is generally written like this:
The code is as follows:
if (!empty($_COOKIE['UserName'])) { $uName=$_COOKIE['UserName']; }
3. Delete the specified cookie
The code is as follows:
setcookie($cookieName,value,time()-秒数); //或者 setcookie($cookiename, ''); //或者 setcookie($cookiename, NULL);
Example: Delete UserName
The code is as follows:
setcookie("UserName","zs",time()-3600);
4. Delete all cookies of the current session
The code is as follows:
foreach($_COOKIE as $key=>$val){ setcookie($key,"",time()-100); }
When there is no cookie, the file that saves the cookie on this machine will also be deleted.
The above is the detailed content of How to use cookies in php?. For more information, please follow other related articles on the PHP Chinese website!