The following is the first to introduce the concept of cookies and working principle.
What is a Cookie?
A Cookie is a small piece of textual information that accompanies the user request and the page is passed between the WEB server and the browser. Each time a user accesses a site, the WEB application can read the information that the Cookie contains.
The basic principle of cookies
If the user accesses a page on the site again, the browser looks for a Cookie associated with the URL on the local hard disk. If the Cookie exists, the browser sends it to your site along with the page request.
What is the use of cookies?
Cookies can help your Web site save information about your visitors. More generally, cookies are a way to keep Web applications continuous. Make the Web site remember you.
After understanding the cookie concept and how it works, let's start by introducing the cookie instance:
First: Create/update cookies
The PHP code to create cookies is as follows:
Setcookie ($cookieName, $value, time () + seconds);
Instance: Create a cookie with the name SiteName, the value is Manong, and the expiration time is 15 days
Setcookie ("UserName", "Zs", Time () +15*24*3600);
Note: If you do not set the time, it will not be saved to the cookie file. When the browser is not off, it can be accessed. When the browser is closed, it cannot be accessed.
Second: Read the value of the cookie
The code to read the value of the cookie is as follows:
$_cookie[$cookieName];
Instance: reads the sitename value and places it in the variable $site
$site =$_cookie[' SiteName '];
When the value is taken, the general judge whether it is empty, and then take the value operation. The above code is not rigorous, the rigorous code should write this:
if (!empty ($_cookie[' sitename '))
{
$site =$_cookie[' SiteName '];
}
Third: Delete cookies
The code to delete the cookie is as follows:
Setcookie ($cookieName, Value,time ()-seconds);
/or
Setcookie ($cookiename, ");
or
Setcookie ($cookiename, NULL);
instance: deleting sitename
Setcookie ("SiteName", "" ", Time ()-3600);
Four: Delete all cookies for the current session
foreach ($_cookie as $key => $val) {
Setcookie ($key, "", Time () -100);
}
Thank you for reading, I hope to help you, thank you for your support for this site!