In this tutorial, you’ll learn how to use the $_COOKIE
superglobal in PHP to manage cookies, allowing you to store user preferences and session data.
PHP Superglobal $_COOKIE
1. What is the $_COOKIE Superglobal?
The $_COOKIE
superglobal is an associative array in PHP that contains all cookies sent to the server by the client. Cookies are small pieces of data stored on the user's computer, which can be used to remember information about the user across requests.
2. Setting Cookies in PHP
To set a cookie in PHP, use the setcookie()
function. This function must be called before any output is sent to the browser:
<?php
setcookie("username", "JohnDoe", time() + 3600, "/"); // Expires in 1 hour
?>
This sets a cookie named username
with the value JohnDoe
, which will expire in one hour.
3. Accessing Cookies with $_COOKIE
You can access cookies using the $_COOKIE
superglobal:
<?php
if (isset($_COOKIE['username'])) {
echo "Username: " . $_COOKIE['username'];
} else {
echo "Username cookie is not set.";
}
?>
4. Deleting Cookies in PHP
To delete a cookie, you can set its expiration date to a time in the past:
<?php
setcookie("username", "", time() - 3600, "/"); // Delete the cookie
?>
This code effectively removes the cookie named username
.
5. Cookie Attributes
When setting a cookie, you can specify various attributes:
- Expires: The time the cookie expires.
- Path: The path on the server where the cookie is available.
- Domain: The domain that the cookie is available to.
- Secure: Indicates whether the cookie should be sent over secure connections only.
- HttpOnly: When set, the cookie is inaccessible to JavaScript, providing protection against XSS attacks.
Example with attributes:
<?php
setcookie("username", "JohnDoe", time() + 3600, "/", "example.com", true, true);
?>
6. Conclusion
The $_COOKIE
superglobal is a powerful tool for managing cookies in PHP. By using cookies, you can store user preferences and maintain session information across different pages. Remember to handle cookies securely and respect user privacy.