PHP Cookie
Cookies are often used to identify users.
What are Cookies?
Cookies are often used to identify users. A cookie is a small file that a server leaves on a user's computer. Each time the same computer requests a page through the browser, the cookie will be sent to the computer. With PHP, you can create and retrieve cookie values.
How to create a cookie?
The setcookie() function is used to set cookies.
Note: setcookie() function must be located before the <html> tag.
Syntax
setcookie(name, value, expire, path, domain);
Example 1
In the following example, we will create a cookie named "user" , and assign it the value "php". We also specify that this cookie expires after one hour:
<?php setcookie("user", "php", time()+3600); ?> <html> .....
Note: When the cookie is sent, the cookie value is automatically changed URL encoding, automatically decoded on retrieval. (To prevent URL encoding, use setrawcookie() instead.)
Example 2
You can also set the cookie expiration time in another way. This may be simpler than using seconds.
<?php $expire=time()+60*60*24*30; setcookie("user", "php", $expire); ?> <html> .....In the above example, the expiration time is set to one month (60 seconds * 60 minutes * 24 hours * 30 days ).
How to retrieve the value of 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 // 输出 cookie 值 echo $_COOKIE["user"]; // 查看所有 cookie print_r($_COOKIE); ?>In the following example , we use the isset() function to confirm whether the cookie has been set:
<html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <?php if (isset($_COOKIE["user"])) echo "欢迎 " . $_COOKIE["user"] . "!<br>"; else echo "普通访客!<br>"; ?> </body> </html>
How to delete cookies?
When deleting a cookie, you should change the expiration date to a point in time in the past.
Deleted instance:
<?php // 设置 cookie 过期时间为过去 1 小时 setcookie("user", "", time()-3600); ?>
What should I do if my browser does not support cookies?
If your application needs to deal with browsers that do not support cookies, then you will have to use other methods to pass information between pages in your application. One way is to pass data through a form (forms and user input are covered in the previous chapters of this tutorial).
The following form submits user input to "welcome.php" when the user clicks the "Submit" button:
<html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <form action="welcome.php" method="post"> 名字: <input type="text" name="name"> 年龄: <input type="text" name="age"> <input type="submit"> </form> </body> </html>retrieves the "welcome.php" file Value, as follows:
<html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> 欢迎 <?php echo $_POST["name"]; ?>.<br> 你 <?php echo $_POST["age"]; ?> 岁了。 </body> </html>