Cookies are the ids which saves the user data into browser and identifies the user next time when the same webpage is opened. Cookies data will save on client-side, in the browser itself. It's not secure compared with Sessions.
Cookie can be created and deleted after particular time automatically or deletion can also be done manually.
Creating Cookies
Syntax
Cookies can be created using setcookie() function.
In the above syntax only one parameter name is required and the remaining are optional.
Example
[php]
<!DOCTYPE html>
<?php
$cookie_name = "Student";
$cookie_value = "Mike";
setcookie($cookie_name, $cookie_value, time() + (5 * 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];
}
?>
<p><strong>Note:</strong> Please reload the page to see the cookie value.</p>
</body>
</html>
[/php]
Output:
One more important thing to be remembered, is setcookie() function had to opened before <html> tag.
The cookie value is URLencoded automatically while the cookie is being sent and gets decoded automatically when received (to avoid URLencoding, setrawcookie() has to be used).
Deleting a Cookie
Example
setcookie() is the function to delete the cookie. Set the cookie expire time to post.
[php]
<!DOCTYPE html>
<?php
// set the expiration date to one hour ago
setcookie("Student", "", time() - 3600);
?>
<html>
<body>
<?php echo "Cookie 'Student' is deleted."; ?>
</body>
</html>
[/php]
Output:
Cookie Enabled or Disabled?
Example
Initially, test cookie need to be created with the function setcookie().Later count the array variable $_COOKIE.
[php]
<!DOCTYPE html>
<?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>
[/php]
Output:
Summary
Points
PHP Cookies can be created and deleted after particular time automatically.
Cookies can be created using setcookie() function.