PHP ยท Chapter 31 of 44

PHP Cookies

Cookies are small pieces of data stored on the user's browser that persist between page visits. PHP creates cookies using setcookie(), and reads them back through the $_COOKIE superglobal on subsequent requests.

Cookies are often used for remembering user preferences, tracking login state, or storing non-sensitive information across sessions. Because cookies are set before any HTML output, setcookie() must be called before anything is sent to the browser.

Syntax
setcookie("name", "value", time() + 3600);
$_COOKIE["name"];

Setting a cookie

setcookie("name", "value", time() + 3600) creates a cookie named "name" that expires in one hour. The cookie is available on the next page load, not the current one.

Reading and deleting cookies

Read a cookie's value using $_COOKIE["name"]. To delete a cookie, call setcookie() again with an expiration time in the past.

Example 1 (php)
<?php
  setcookie("user", "Amy", time() + 3600);
?>
Output
(cookie set for next request)

This sets a cookie named user with the value Amy, expiring in one hour.

Example 2 (php)
<?php
  if (isset($_COOKIE["user"])) {
    echo "Welcome back, " . $_COOKIE["user"];
  }
?>
Output
Welcome back, Amy

On a later request, $_COOKIE reads back the previously stored value.

Key points

  • setcookie() creates a cookie on the client's browser.
  • Cookies are available starting from the next page load.
  • $_COOKIE reads cookie values sent by the browser.
  • Deleting a cookie means setting it with a past expiration time.
๐Ÿ’ก Note: Never store sensitive information like passwords directly in cookies, since users can view and modify them.

๐Ÿ“ Quick Quiz

1. Which function creates a cookie in PHP?

2. Which superglobal reads cookie values?

3. When does a newly set cookie become available to read?