How to use cookies in php?

怪我咯
Release: 2023-03-13 10:36:01
Original
2013 people have browsed it

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()+秒数);
Copy after login

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);
Copy after login

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");
Copy after login

2. Get the value of cookie

The code is as follows:

$_cookie[$cookieName];
Copy after login

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

The code is as follows:

$uName=$_COOKIE['UserName'];
Copy after login

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'];
}
Copy after login

3. Delete the specified cookie

The code is as follows:

setcookie($cookieName,value,time()-秒数);
//或者
setcookie($cookiename, '');
//或者
setcookie($cookiename, NULL);
Copy after login

Example: Delete UserName

The code is as follows:

setcookie("UserName","zs",time()-3600);
Copy after login

4. Delete all cookies of the current session

The code is as follows:

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

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!

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!