PHP Cookies

Cookies are commonly used to identify users.

What is a Cookie?

Cookies are commonly used to identify users. Cookies are small files left by the server on the user's computer. Whenever the same computer requests a page through a browser, it also sends the cookie. With PHP, you can create and retrieve the value of cookies.

How to create a cookie?

The setcookie() function is used to set cookies.

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

Syntax

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

Example

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

<?php 
setcookie("user", "Alex Porter", time()+3600);
?>
<html>
<body>
</body>
</html>

Note:When sending a cookie, the value of the cookie is automatically URL-encoded, and it is automatically decoded when retrieved (to prevent URL encoding, use setrawcookie() instead).

How to retrieve the value of a Cookie?

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

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

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

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

<html>
<body>
<?php
if (isset($_COOKIE["user"]))
  echo "Welcome " . $_COOKIE["user"] . "!<br />";
else
  echo "Welcome guest!<br />";
?>
</body>
</html>

How to delete a cookie?

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

Example of deletion:

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

What should you do if the browser does not support cookies?

What if your application involves browsers that do not support cookies? You would have to take other methods to pass information from one page to another in the application. One way is to pass data from the form (we have already introduced the content of forms and user input earlier in this tutorial).

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

<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name" />
Age: <input type="text" name="age" />
<input type="submit" />
</form>
</body>
</html>

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

<html>
<body>
Welcome <?php echo $_POST["name"]; ?>.<br />
You are <?php echo $_POST["age"]; ?> years old.
</body>
</html>