PHP Cookies


What is a Cookie?

A cookie is often used to identify a user. A cookie is a small file server embedded in a user's computer. Each time the same computer requests a page with a browser, it will send a cookie again. With PHP, you can create and return cookie values.


Create Cookies With PHP

A cookie is created by a setcookie() function.

Syntax
setcookie(name, value, expire, path, domain, secure, httponly);

Only the word parameter is required. All other parameters are optional.


PHP Create/Retrieve a Cookie

The following example creates a cookie called "user" with the value "John Doe". The cookie will expire after 30 days (86400 * 30). "/" Means that the cookie is available throughout the website (otherwise, select your favorite directory).

We then return the "user" cookie value (using the global variable $ _COOKIE). We also use the isset() function to determine if a cookie is set:


Example
<?php
$cookie_name = "user";
$cookie_value = "John Doe";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/"); // 86400 = 1 day
?>

<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
  echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
  echo "Cookie '" . $cookie_name . "' is set!<br>";
  echo "Value is: " . $_COOKIE[$cookie_name];
}
?>


</body>
</html>


Note: The setcookie() function must appear BEFORE the tag.


Note: The cookie value is encrypted with the URL automatically when the cookie is sent, and it is automatically removed when it is received (to prevent URL encoding, use setrawcookie() instead).


Modify a Cookie Value

To modify cookies, simply set (and) cookies using the setcookie() function:


Example
<?php
$cookie_name = "user";
$cookie_value = "Alex Porter";
setcookie($cookie_name, $cookie_value, time() + (86400 * 30), "/");
?>

<html>
<body>

<?php
if(!isset($_COOKIE[$cookie_name])) {
  echo "Cookie named '" . $cookie_name . "' is not set!";
} else {
  echo "Cookie '" . $cookie_name . "' is set!<br>";
  echo "Value is: " . $_COOKIE[$cookie_name];
}
?>


</body>
</html>


Delete a Cookie

To clear cookies, use a setcookie() function with an expiration date:


Example
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>

<html>
<body>

<?php
echo "Cookie 'user' is deleted.";
?>


</body>
</html>


Check if Cookies are Enabled

The following example creates a small text that checks whether cookies are enabled. First, try making a test cookie with setcookie() function, then calculate $ _ COOKIE of variable array:


Example
<?php
setcookie("test_cookie", "test", time() + 3600, '/');
?>

<html>
<body>

<?php
if(count($_COOKIE) > 0) {
  echo "Cookies are enabled.";
} else {
  echo "Cookies are disabled.";
}
?>


</body>
</html>