PHP - HTML Cookies

Introduction

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.

example

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"> 
    <body> 
        <p>Enter your details to login:</p> 
        <form action="authenticate.php" method="post"> 
            <label>Username</label> 
           <input type="text" name="username" /> 
            <label>Password</label> 
           <input type="password" name="password" /> 
            <input type="submit" value="Login"/> 
        </form> 
    </body> 
</html> 

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

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

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