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:
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"> <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.