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! π―
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.
$_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.
To create a cookie in PHP, you can use the setcookie() function. Here's a simple example:
<?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.
To read cookies in PHP, you can access the $_COOKIE superglobal variable. Here's an example:
<?php
// Read the username cookie
echo $_COOKIE["username"]; // Outputs: John Doe
?>To delete a cookie in PHP, you can set its expiration date to be in the past. Here's an example:
<?php
// Delete the username cookie
setcookie("username", "", time() - 3600); // Expires 1 hour ago
?>Let's see a simple login system that uses cookies to remember the user's username.
<?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>What does the `setcookie()` function do in PHP?
Happy coding! If you found this tutorial helpful, consider sharing it with your friends. π