Day 19: Cookies in PHP

Cookie is used to store information of a web page. It’s often used to identify user by embedding small file on the user’s computer. When same computer requests a page with a browser, it will send the cookie too.

There are 2 types of cookies:

  1. Temporary cookies: saved in browser’s memory. Erased when browser closed.
  2. Persistent cookies: saved as a text file in the file system of client PC.

setcookie() is a function used to create a cookie in php.

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

setcookie function has below parameters:

Parameter Description Data Type
name Specifies the name of the cookie | Required String
value Specifies the value of the cookie | Optional String
expire Specifies cookie expires time. time()+86400*1, will set the cookie to expire in 1 day. | Optional Integer
path Server path in which the cookie will be available. | Optional String
domain To which domain the cookie is available. | Optional String
secure If set true, the cookie is available over secure connection only. | Optional Boolean
httponly If set true, the cookie is available over HTTP protocol only. | Optional Boolean

Program 56: Create and Retrieve a Cookie

<?php
$cookieName = “name”;
$cookieValue = “Albert”;
setcookie($cookieName, $cookieValue, time() + (86400 * 1), “/”); /* epiry time : 1day */
if(isset($_COOKIE[$cookieName])) {
echo “Cookie Name: ” . $cookieName;
echo “
Cookie Value: ” . $_COOKIE[$cookieName]; /* displaying cookie value. */
} else {
echo “Cookie not set!”;
}
?>

Program 57: Modify a Cookie Value

<?php
$cookieName = “name”;
$cookieValue = “Albert Hedsan”;
setcookie($cookieName, $cookieValue, time() + (86400 * 1), “/”);
if(isset($_COOKIE[$cookieName])) {
echo “
Cookie value updated: ” . $_COOKIE[$cookieName];
}
?>

Program 58: Delete a Cookie

<?php
setcookie(“user”, “”, time() – 3600);
/* to delete the cookie, set the expiration date to one hour back*/
echo “cookie is deleted!”;
?>

One common use of cookies is to save username and password on your computer, so you don’t need to login again and again each time you visit a website. Cookies can also store other values like: user name, user password, shopping cart contents, etc.

No Responses

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.