PHP $_COOKIE Reference

beginner
18 min

PHP $_COOKIE Reference

Welcome to our comprehensive guide on PHP's $_COOKIE! This tutorial is designed to help beginners and intermediates understand how to work with cookies in PHP. Let's dive in! 🎯

What are Cookies? πŸ“

Cookies are small pieces of data stored on a user's computer by their web browser. They are used to remember information about the user, such as their preferences or login details, across multiple visits to a website.

PHP's $_COOKIE πŸ’‘

In PHP, $_COOKIE is an array-like superglobal variable that contains all the cookies sent to the current script. Let's see how to create, read, and delete cookies using PHP.

Creating Cookies πŸ“

To create a cookie in PHP, you can use the setcookie() function. Here's a simple example:

php
<?php // Create a cookie named "username" with the value "John Doe" setcookie("username", "John Doe", time() + (86400 * 30)); // Expires in 30 days ?>

πŸ“ Note: The third argument is the expiration time (in seconds) for the cookie. By default, cookies expire when the browser is closed.

Reading Cookies πŸ“

To read cookies in PHP, you can access the $_COOKIE superglobal variable. Here's an example:

php
<?php // Read the username cookie echo $_COOKIE["username"]; // Outputs: John Doe ?>

Deleting Cookies πŸ“

To delete a cookie in PHP, you can set its expiration date to be in the past. Here's an example:

php
<?php // Delete the username cookie setcookie("username", "", time() - 3600); // Expires 1 hour ago ?>

Real-world Examples 🎯

Let's see a simple login system that uses cookies to remember the user's username.

php
<?php // Login form submission if (isset($_POST["login"])) { // Verify login details (in real projects, use secure methods) if ($_POST["username"] == "john" && $_POST["password"] == "password") { // Set a cookie with the username setcookie("username", $_POST["username"], time() + (86400 * 30)); // Expires in 30 days // Redirect to homepage header("Location: home.php"); exit(); } } ?> <!-- Login form --> <form method="post"> <label for="username">Username:</label> <input type="text" name="username" /> <br /> <label for="password">Password:</label> <input type="password" name="password" /> <br /> <input type="submit" name="login" value="Login" /> </form>

Quiz πŸ’‘

Quick Quiz
Question 1 of 1

What does the `setcookie()` function do in PHP?

Happy coding! If you found this tutorial helpful, consider sharing it with your friends. πŸš€