Home > Backend Development > PHP Tutorial > Advanced PHP Tutorial: PHP Cookies

Advanced PHP Tutorial: PHP Cookies

黄舟
Release: 2023-03-03 15:36:01
Original
1435 people have browsed it

Cookies are often used to identify users.

What are Cookies?

Cookies are often used to identify users. Cookies are small files that a server leaves on a user's computer. Whenever the same computer requests a page through the browser, it also sends the cookie. With PHP, you can create and retrieve cookie values.

How to create cookies?

setcookie() function is used to set cookies.

Note: The setcookie() function must be placed before the tag.

Syntax

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

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

setcookie("user", "Alex Porter", time()+3600);
?>


Note: When sending a cookie, the cookie value will be automatically URL-encoded and automatically decoded when retrieved (to prevent URL encoding, please use setrawcookie() instead).
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:

// Print a cookie
echo $_COOKIE["user "];
// A way to view all cookies
print_r($_COOKIE);
?>

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


if (isset($_COOKIE["user"]))
echo "Welcome " . $_COOKIE["user"] . "!
";
else
echo "Welcome guest!
";
?>

How to delete cookies?

When deleting a cookie, you should change the expiration date to a point in time in the past.

Example of deletion:

// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>

If the browser does not What should I do if I support cookies?

If your application involves browsers that do not support cookies, you will have to use other methods to pass information from one page to another in your application. One way is to pass data from a form (we've covered forms and user input earlier in this tutorial).

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




Name:
Age:



Retrieve the value in "welcome.php" like this:


Welcome .

You are years old.

< ;/html>

The above is the content of the PHP Advanced Tutorial: PHP Cookies. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template