In this PHP tutorial, you will learn all about Cookies in PHP. We will also discuss how to create cookies, check cookies, access cookies, and delete cookies.
A cookie is a tiny file with a maximum size of nearly 4KB that is stored in the client computer by the webserver. They are often used to save information like username, which helps the users to view the customized web pages according to the user whenever they visit the website next. A cookie can only be read from the domain from which it was issued. Cookies are typically put in an HTTP header, but JavaScript may also establish a cookie on a browser directly.
To create cookies in PHP we use the function setcookie(). The setcookie() method must be called before any script output is created, else the cookie will not be set.
Syntax
setcookie(name, value, expire, path, domain, security);
In the setcookie() function we pass the arguments:
Example
setcookie("username", "john", time()+2*24*60*60);
It is always preferred to check whether the cookie is set perfectly or not before trying to access it. To check whether the cookie is set or not in PHP we use the isset() function which will return TRUE if the cookie is available.
Example
if (isset($_COOKIE['username'])) { echo "Cookie is available"; } else { echo "Cookie is not available"; }
Output:
Cookie is not available
To access a cookie value, we use the PHP $_COOKIE[] superglobal variable or $HTTP_COOKIE_VARS[] variables. It is often an associative array containing a list of all cookie values given by the browser in the current request, keyed by cookie name. Using normal array syntax, the individual cookie value may be obtained.
Example
<?php
setcookie("username", "john", time() + 2 * 24 * 60 * 60);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Cookies Sample Program</title>
</head>
<body>
<?php
if (isset($_COOKIE['username'])) {
echo "<h1> The username is " . $_COOKIE['username'] . "</h1>";
} else {
echo "Cookie is not available";
}
?>
</body>
</html>
To remove a cookie, we use the same setcookie() method. To delete a cookie, the setcookie() function is used with the cookie name defined earlier and additional parameters or empty strings, but this time the expiration date must be set in the past.
Example
<?php
setcookie("username", "", time() - 60000);
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title>Cookies Sample Program</title>
</head>
<body>
<?php
if (isset($_COOKIE['username'])) {
echo "<h1> The username is " . $_COOKIE['username'] . "</h1>";
} else {
echo "<h1> Cookie is not available... </h1>";
}
?>
</body>
</html>