Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

PHP Cookie

PHP Cookie


Cookies are commonly used to identify users.


What is a Cookie?

Cookies are commonly 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 will send the cookie. With PHP, you can create and retrieve the value of a cookie.


How to Create a Cookie?

The setcookie() function is used to set a cookie.

**Note:** The setcookie() function must appear before the tag.

Syntax



setcookie(name, value, expire, path, domain);

Example 1

In the example below, we will create a cookie named "user" and assign it the value "runoob". We also specify that this cookie expires after one hour:









.....

**Note:** When sending a cookie, its value is automatically URL-encoded and automatically decoded when retrieved. (To prevent URL encoding, use setrawcookie() instead.)

Example 2

You can also set the cookie's expiration time in another way. This may be simpler than using seconds.









.....

In the example above, the expiration time is set to one month (60 seconds * 60 minutes * 24 hours * 30 days).


How to Retrieve the Value of a Cookie?

PHP's $_COOKIE variable is used to retrieve the value of a cookie.

In the example below, we retrieve the value of the cookie named "user" and display it on the page:





In the example below, we use the isset() function to check whether the cookie has been set:









Runoob Tutorial(runoob.com)







";

else

    echo "普通访客!
"; ?>

How to Delete a Cookie?

When deleting a cookie, you should set its expiration date to a past point in time.

Example of deletion:






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 ways to pass information between pages in your application. One way is to pass data through forms (we have covered forms and user input in earlier chapters of this tutorial).

The form below submits the user's input to "welcome.php" when the user clicks the "Submit" button:









Runoob Tutorial(runoob.com)







名字: 年龄:

Retrieve the value in the "welcome.php" file, as shown below:









Runoob Tutorial(runoob.com)







欢迎 .
你 岁了。