Can PHP Send and Receive Cookies?
Yes, PHP can both send (set) and receive (read) cookies.
Cookies are a mechanism for storing data in the user’s web browser and tracking or identifying return users. They are part of the HTTP protocol, and PHP has built-in features to work with them.
Setting a Cookie
You can set a cookie in PHP using the setcookie()
function. Here is a basic example:
<?php
// set a cookie named "user" with the value "John Doe" to expire in one hour
setcookie("user", "John Doe", time() + 3600);
?>
The setcookie()
function must be called before any output is sent to the browser. If you’ve already sent output, you’ll get an error if you try to set a cookie.
The third argument to setcookie()
is the expiration time. time()
returns the current time, and + 3600
adds one hour to it, so this cookie will last for one hour.
Reading a Cookie
To read a cookie in PHP, you can access the $_COOKIE
superglobal array. Here is a basic example:
<?php
if(!isset($_COOKIE["user"])) {
echo "Welcome, guest!";
} else {
echo "Hello, " . $_COOKIE["user"];
}
?>
This script checks if a cookie named “user” is set. If it’s not set, it outputs “Welcome, guest!”. If it is set, it outputs “Hello, " followed by the value of the cookie.
Deleting a Cookie
To delete a cookie, you can call setcookie()
with an expiration date in the past:
<?php
// set the cookie "user" to expire one hour ago
setcookie("user", "", time() - 3600);
?>
After running this script, the “user” cookie will be deleted from the user’s browser.