This tutorial aims to provide a comprehensive guide on how to use cookies for user management using PHP.
By the end of this tutorial, you will be able to:
- Understand what cookies are and how they work.
- Set, retrieve, and delete cookies using PHP.
- Use cookies for managing user sessions and preferences.
You should have a basic understanding of PHP and HTML.
A cookie is a small piece of data stored on the user's computer by the web browser while browsing a website. Cookies were designed to be a reliable mechanism for websites to remember stateful information or to record the user's browsing activity.
To manage cookies, PHP provides three functions:
1. setcookie()
: To set a new cookie.
2. $_COOKIE
: A superglobal array holding all cookies.
3. setcookie()
: To delete a cookie.
A cookie is set using the setcookie()
function. This function must appear BEFORE the <html>
tag.
<?php
setcookie(name, value, expire, path, domain, secure, httponly);
?>
name
: Name of the cookie.value
: Content of the cookie.expire
: Expiry date and time of the cookie.path
, domain
, secure
, httponly
are optional parameters.Cookies are retrieved using PHP's $_COOKIE
variable, an associative array of variables passed to the current script via HTTP Cookies.
<?php
echo $_COOKIE["user"];
?>
A cookie is deleted by setting the expiration date to an already passed time.
<?php
setcookie("user", "", time() - 3600);
?>
<?php
setcookie("username", "John Doe", time() + (86400 * 30)); // 86400 = 1 day
?>
This sets a cookie named "username" with the value "John Doe". The cookie will expire after 30 days.
<?php
if(!isset($_COOKIE["username"])) {
echo "Cookie named 'username' is not set!";
} else {
echo "Cookie 'username' is set!<br>";
echo "Value is: " . $_COOKIE["username"];
}
?>
This script checks if a cookie named "username" has been set. If yes, it retrieves and prints the value.
<?php
setcookie("username", "", time() - 3600);
?>
This sets the "username" cookie's expiration date to one hour in the past, effectively deleting it.
We've covered how to set, retrieve, and delete cookies using PHP. We also learnt how cookies can be used for managing user sessions and preferences. Now you can apply these concepts to manage user data in your PHP applications.
Remember to test your scripts after each change. Happy coding!
For further reading, check out the PHP Cookies Documentation.