Cookies are often used to identify users.
What is a Cookie?
Cookies are often used to identify users. A cookie is a small file that the server leaves on the user's computer. Whenever the same computer requests a page through a browser, it also sends a cookie. 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);
In the following example, we will create a cookie named "User" and assign it a value of "Alex Porter". We also stipulate that this cookie expires after one hour:
<?php
Setcookie ("User", "Alex Porter", Time () +3600);
?>
<body>
</body>
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).
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
Print a cookie
echo $_cookie["user"];
A-to-View all cookies
Print_r ($_cookie);
?>
In the following example, we use the Isset () function to confirm whether a cookie has been set:
<body>
<?php
if (Isset ($_cookie["user"))
echo "Welcome". $_cookie["User"]. "!<br/>";
Else
echo "Welcome guest!<br/>";
?>
</body>
How do I delete cookies?
When you delete a cookie, you should change the expiration date to a past point in time.
Examples of deletions:
<?php
Set the expiration date to one hour ago
Setcookie ("User", "", Time ()-3600);
?>
What if the browser does not support cookies?
If your application involves a browser that does not support cookies, you will have to take a different approach to passing information from one page to another in your application. One way to do this is to pass data from the form (about the form and what the user entered, as we've already covered in this tutorial earlier).
The following form submits user input to "welcome.php" when the user clicks the Submit button:
<body>
<form action= "welcome.php" method= "POST" >
Name: <input type= "text" name= "name"/>
Age: <input type= "text" name= "age"/>
<input type= "Submit"/>
</form>
</body>
<body>
Welcome <?php echo $_post["name"];? >.<br/>
You is <?php echo $_post["age",?> years old.
</body>
The above is the PHP Advanced Tutorial: PHP cookies content, more relevant content please pay attention to topic.alibabacloud.com (www.php.cn)!