What is a cookie in PHP?
In PHP, a cookie is a small piece of data stored on the client-side (in the user's web browser) that can be used to remember information about the user between different pages or visits. Cookies are commonly used for various purposes, such as tracking user sessions, storing user preferences, or managing login states.
Here’s a basic overview of how cookies work in PHP:
-
Setting a Cookie: You use the
setcookie()
function to create a cookie. This function must be called before any output is sent to the browser, including HTML or whitespace.setcookie("username", "JohnDoe", time() + 3600, "/");
"username"
is the name of the cookie."JohnDoe"
is the value of the cookie.time() + 3600
sets the cookie to expire in 1 hour (3600 seconds)."/"
specifies the path on the server where the cookie is available. The default is the current directory.
-
Retrieving a Cookie: Once a cookie is set, you can access it using the
$_COOKIE
superglobal array.if (isset($_COOKIE["username"])) { echo "Username is: " . $_COOKIE["username"]; } else { echo "Cookie 'username' is not set."; }
-
Deleting a Cookie: To delete a cookie, you set its expiration date to a time in the past.
setcookie("username", "", time() - 3600, "/");
Here, the cookie named
"username"
is set to expire immediately by setting its expiration time to an hour in the past.
Cookies are a powerful tool for managing user sessions and preferences, but they should be used cautiously to avoid security issues, such as ensuring sensitive information is not stored in cookies and using secure cookie attributes.
At Online Learner, we're on a mission to ignite a passion for learning and empower individuals to reach their full potential. Founded by a team of dedicated educators and industry experts, our platform is designed to provide accessible and engaging educational resources for learners of all ages and backgrounds.
Copyright 2023-2025 © All rights reserved.