PHP cookies play an important role in PHP caching, and this article provides some detailed information about them.
What is a Cookie?
Cookies are often used to identify users. A cookie is a small file that a server leaves on a user's computer. This computer sends a cookie whenever a page is requested by the same computer through a browser. With PHP, you can create and retrieve the value of a cookie.
How do I create a Cookie?
The Setcookie () function is used to set cookies.
Note: the Setcookie () function must precede the
Grammar
Setcookie (name, value, expire, path, domain);
Example 1
In the following example, we will create a cookie named "User" and assign it a value of "Runoob". We also stipulate that this cookie expires after one hour:
<?phpsetcookie ("User", "Runoob", Time () +3600); >
Note: When a cookie is sent, the value of the cookie is automatically URL-encoded and automatically decoded upon retrieval. (To prevent URL encoding, use Setrawcookie () instead.) )
Example 2
You can also set the expiration time of a cookie in another way. This may be simpler than using the second representation.
<?php$expire=time () +60*60*24*30;setcookie ("User", "Runoob", $expire);? >
In the above instance, the expiration time is set to one months (60 seconds * 60 Minutes * 24 hours * 30 days).
How do I retrieve the value of a Cookie?
PHP's $_cookie variable is used to retrieve the value of the COOKIE.
In the following example, we retrieve the value of the cookie named "User" and display it on the page:
<?php//Output Cookie value echo $_cookie["user"];//View all Cookieprint_r ($_cookie);? >
In the following example, we use the Isset () function to confirm whether a cookie has been set:
How do I delete cookies?
When you delete a cookie, you should change the expiration date to a past point in time.
Deleted instances:
<?php//Set cookie expires in the last 1 hours setcookie ("User", "", Time ()-3600); >
What if the browser does not support cookies?
If your application needs to deal with browsers that do not support cookies, then you have to use other means to pass information between pages in your application. One way to do this is to pass data through the form (for forms and user input, as we've covered in the previous chapters of this tutorial).
The following form submits user input to "welcome.php" when the user clicks the "Submit" button:
Retrieve the value from the "welcome.php" file as follows:
This article on the knowledge of the Cookie has made a detailed understanding, more learning materials to clear attention to the PHP Chinese network can be viewed.