PHP Tutorials
PHP Forms
PHP Advanced
PHP OOP
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.
A cookie is created by a setcookie()
function.
setcookie(name, value, expire, path, domain, secure, httponly);
Only the word parameter is required. All other parameters are optional.
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:
<?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).
To modify cookies, simply set (and) cookies using the setcookie()
function:
<?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>
To clear cookies, use a setcookie()
function with an expiration date:
<?php
// set the expiration date to one hour ago
setcookie("user", "", time() - 3600);
?>
<html>
<body>
<?php
echo "Cookie 'user' is deleted.";
?>
</body>
</html>
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:
<?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>