PHP development basic tutorial - Cookie
1. 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.
2. How to create a cookie?
The setcookie() function is used to set cookies.
Note: The setcookie() function must be located before the <html> tag.
Syntax
setcookie(name, value, expire, path, domain);
Example: The code is as follows
In the following example, we will create a cookie named "user" and assign it the value "php". We have also specified that this cookie will expire after one minute:
<?php setcookie("user", "php", time()+60); ?>
You can also set the cookie expiration time in another way
<?php $expire=time()+60; setcookie("user", "php",$expire); ?>
3. 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:
The code is as follows
<html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <?php // 输出 cookie 值 echo $_COOKIE["use"]; ?> </body> </html>
In the following example, we use the isset() function to confirm whether the cookie has been set:
The code is as follows:
<html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> </head> <body> <?php //判断cookie数据是否存在 if (isset($_COOKIE["user"])) echo "欢迎 " . $_COOKIE["user"] . "!<br>"; else echo "普通访客!<br>"; ?> </body> </html>
4. 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); ?>