cookies

PHP Cookies

PHP Cookies

Cookies are small files that are stored on the user's computer. PHP allows you to set, retrieve, and delete cookies.

Setting a Cookie

To set a cookie in PHP, use the setcookie() function:

      
        <?php
          setcookie("username", "JohnDoe", time() + 3600); // Cookie expires in 1 hour
          echo "Cookie set!";
        ?>
      
    

Accessing a Cookie

To access the value of a cookie, use the $_COOKIE superglobal:

      
        <?php
          if(isset($_COOKIE['username'])) {
            echo "Hello, " . $_COOKIE['username'];
          } else {
            echo "Cookie not set.";
          }
        ?>
      
    

Deleting a Cookie

To delete a cookie, set its expiration time to a past time:

      
        <?php
          setcookie("username", "", time() - 3600); // Delete the cookie
          echo "Cookie deleted!";
        ?>
      
    

Activity

Try It Yourself!

Set a cookie with your name and display it on a new page.

Quiz

Quick Quiz

  1. What function is used to set a cookie in PHP?
  2. How can you access a cookie in PHP?

Answers: Use setcookie() to set a cookie. Access cookies using the $_COOKIE superglobal.