Home  >  Article  >  Backend Development  >  What does Cookie mean in PHP?

What does Cookie mean in PHP?

Guanhui
GuanhuiOriginal
2020-06-28 11:01:203726browse

Cookie is often used to identify users. It is a small file left by the server on the user's computer. Whenever the same computer requests a page through the browser, this computer will send the Cookie. Through PHP, the user can Create and retrieve cookie values.

What does Cookie mean in PHP?

Recommended tutorial: "PHP Cookie-based Shopping Cart Module Design"

How to create a cookie?

The setcookie() function is used to set cookies.

Note: The setcookie() function must be located before the 100db36a723c770d327fc0aef2ce13b1 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 "runoob". We also specify that this cookie expires after one hour:

<?php
setcookie("user", "runoob", time()+3600);
?>
<html>
.....

Note: The cookie value is automatically URL-encoded when sending the cookie and automatically decoded when retrieved. (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", "runoob", $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 isset() function to confirm whether the cookie has been set:

<html>
<head>
<meta charset="utf-8">
<title>菜鸟教程(runoob.com)</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);
?>

Recommended tutorial: "PHP Tutorial"

The above is the detailed content of What does Cookie mean in PHP?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn