Home  >  Article  >  Backend Development  >  How to use cookies in php_PHP tutorial

How to use cookies in php_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:35:06925browse

1. Create/update cookies

Copy code The code is as follows:

setCookie($cookieName,$value,time ()+seconds);

Example: Create a cookie with the name UserName, value zs, and expiration time of 2 weeks

Copy code The code is as follows:

setcookie("UserName","zs",time()+2*7*24*3600);

If the time is not set, it will not be saved to the cookie file. It can be accessed when the browser is not closed. When the browser is closed, it is no longer accessible.

Example:

Copy code The code is as follows:

setcookie("Age","18");

2. Get the value of cookie

Copy the code The code is as follows:

$_cookie[$cookieName];

Example: Take out the value of UserName and put it in the variable $uName

Copy the code The code is as follows:

$uName =$_COOKIE['UserName'];

When getting a value, it is generally judged whether it is empty before performing the value operation. The above value operation is generally written like this:

Copy the code The code is as follows:

if (!empty($_COOKIE[' UserName']))
{

$uName=$_COOKIE['UserName'];

}

3. Delete the specified cookie

Copy code The code is as follows:

setcookie($cookieName,value,time() - seconds);
//or
setcookie($cookiename, '');
//or
setcookie($cookiename, NULL);


Example: Delete UserName

Copy code The code is as follows:

setcookie("UserName","zs ",time()-3600);

4. Delete all cookies for the current session

Copy code The code is as follows:

foreach($_COOKIE as $key =>$val){
setcookie($key,"",time()-100);
}

When there are no cookies, the files that save cookies on this machine will also be deleted.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/746866.htmlTechArticle1. Create/update cookie Copy code The code is as follows: setCookie($cookieName,$value,time()+seconds Number); Example: Create a cookie with the name UserName, value zs, and expiration time of 2 weeks...
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