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:

ParameterDescriptionData Type
nameSpecifies the name of the cookie | RequiredString
valueSpecifies the value of the cookie | OptionalString
expire Specifies cookie expires time. time()+86400*1, will set the cookie to expire in 1 day. | OptionalInteger
pathServer path in which the cookie will be available. | OptionalString
domainTo which domain the cookie is available. | OptionalString
secureIf set true, the cookie is available over secure connection only. | OptionalBoolean
httponlyIf set true, the cookie is available over HTTP protocol only. | OptionalBoolean

Program 56: Create and Retrieve a Cookie

$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

$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

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