PHP Cookies
What exactly is a cookie?
A cookie is a small text file that allows you to save a small amount of data on the user's machine (nearly 4KB). They are commonly used to keep track of details such as usernames that the site may use to personalize the page when the user returns to the site.
Using PHP to Build a Cookie
In PHP, the setcookie()
function is used to create a cookie. If you don't call the setcookie()
function before any output from your script, the cookie won't be set. The following is the basic syntax for this function:
setcookie(name, value, expire, path, domain, secure);
Here's an example of how to use the setcookie()
function to construct a username cookie with the value John Carter. The cookie will also expire after 30
days (30 days * 24 hours * 60 minutes * 60 seconds)
.
<?php
// Setting a cookie
setcookie("username", "John Carter", time()+30*24*60*60);
?>
Values of Cookies Can Be accessed
To get a cookie value, use the PHP $_COOKIE
superglobal variable. It's usually an associative array that's keyed by cookie name and includes a list of all the cookies values sent by the browser in the current request. Individual cookie values can be accessed using standard array notation, such as the following code to show the username cookie set in the previous example.
<?php
// Accessing an
// individual cookie value
echo $_COOKIE["username"];
?>
Before accessing a cookie's value, it's a good idea to verify if it's set or not. You can do this by using the PHP isset()
module, which looks like this:
<?php
// Verifying whether
// a cookie is set
// or not
if(isset($_COOKIE["username"])){
echo "Hi " . $_COOKIE["username"];
}
else{
echo "Welcome Guest!";
}
?>
To see the layout of this $_COOKIE
associative array, use the print r()
function like print r($ COOKIE)
; as you would for any other array.
How to delete a Cookie
You can delete a cookie by using the same setcookie()
function with the cookie name and any value (such as an empty string), but you must set the expiration date in the past this time, as seen in the example below:
<?php
// How to delete a cookie
setcookie("username", "", time()-3600);
?>