PHP - HTML Cookies


To let browser to remember some data like whether you are logged in or not on your web application, your basic info, and so on, use cookies.

Cookies are stored on the client side and are sent to the server when making a request as headers.

PHP can manage cookies in a very easy way.

You can write cookies with the setcookie function that accepts several arguments:

  • A valid name for the cookie as a string.
  • The value of the cookie-only strings or values that can be casted to a string. This parameter is optional, and if not set, PHP will actually remove the cookie.
  • Expiration time as a timestamp. If not set, the cookie will be removed once the browser is closed.

You can only set cookies if there is no previous output from your application, that is, before HTML, echo calls, and any other similar functions that send some output.

To read the cookies that the client sends to us, access the array, $_COOKIE.

The keys of the array will be the name of the cookies and the value of the array will be their values.


A common usage for cookies is authenticating the user.

The following code shows a simple and insecure one.

Here is the login.html and go to http://localhost:8000/login.html.

<!DOCTYPE html> 
<html lang="en"> 
        <p>Enter your details to login:</p> 
        <form action="authenticate.php" method="post"> 
           <input type="text" name="username" /> 
           <input type="password" name="password" /> 
            <input type="submit" value="Login"/> 

Update the PHP part of your authenticate.php file with the following content:

     setcookie('username', $_POST['username']); 
     $submitted = !empty($_POST); 
        <p>You are <?php echo $_COOKIE['username']; ?></p> 

If you access http://localhost:8000/login.html again, try to log in, open a new tab (in the same browser), and go to the home page at http://localhost:8000, you will see how the browser still remembers your username.

Related Topics