A Comprehensive Guide to PHP Superglobals: Understanding Cookies
A Comprehensive Guide to PHP Superglobals: Understanding Cookies
PHP superglobals are built-in variables that are always accessible, regardless of scope. One of these superglobals is $_COOKIE
, which is used to handle cookies in PHP.
What are Cookies?
- Definition: Cookies are small pieces of data stored on the user's computer by the web browser while browsing a website.
- Purpose: They are used to remember information about the user, such as login credentials or preferences.
The $_COOKIE
Superglobal
- Definition:
$_COOKIE
is an associative array in PHP that contains all cookies sent by the client to the server. - Accessing Cookies: You can access cookie values using their names as keys in the
$_COOKIE
array.
Setting Cookies
To set a cookie in PHP, you use the setcookie()
function:
setcookie("username", "JohnDoe", time() + (86400 * 30), "/"); // 86400 = 1 day
- Parameters:
- Name: The name of the cookie (
"username"
in this example). - Value: The value of the cookie (
"JohnDoe"
). - Expiration: The time until the cookie expires (in this case, 30 days from now).
- Path: The path on the server where the cookie will be available (
"/"
means it is available across the entire domain).
- Name: The name of the cookie (
Retrieving Cookies
To retrieve a cookie, simply access it through the $_COOKIE
superglobal:
if (isset($_COOKIE["username"])) {
echo "Username is: " . $_COOKIE["username"];
} else {
echo "Username cookie is not set.";
}
- Checking Existence: Always check if a cookie is set using
isset()
to avoid errors.
Deleting Cookies
To delete a cookie, you can set its expiration date to a past time:
setcookie("username", "", time() - 3600, "/"); // Deletes the cookie
Key Concepts to Remember
- Cookies are stored on the client's machine and sent to the server with every request.
- The
$_COOKIE
array is used to access cookie values. - Always check if a cookie exists before accessing it.
- Cookies can be set to expire after a certain period or can be deleted by setting a past expiration date.
By understanding how to use cookies in PHP through the $_COOKIE
superglobal, you can enhance user experience by remembering user preferences and maintaining session states.