Saturday, November 22, 2014

How to Develop, Set, Read and Delete Cookie in PHP

As we all know that, cookies are very useful to store the information in user or remote browser. It is a basic text file which has a capacity to store 4 GB data. Every single time, when a user visit to any website, it sets the cookie. The browser sends previous cookie information back to the server with using HTTP Header.

Why Cookies are Useful???

HTTP is a stateless, so there are no way to track user's activities on the website. So, cookie is the best way to store the information like number of time user visit on a website.

How to Set Cookie in PHP :-

setcookie() function is useful to set the cookie in PHP.

Syntax :-

setcookie(name,value,time,path,domain,secure);
Name – Defines the name of a cookie.

Value :– Cookies always store string value. If you want to store array value in a cookie, then Click Here to learn that how to store array value in cookies.

Time :– Set the expiry date for cookie. If this field is empty, then the cookie will be deleted when the browser is closed. It is an optional field.

Domain :– You can set domain in which the cookie is available. If you want to set the cookie for multiple subdomains, then use the name of main domain with dot as a prefix.

For Example :- Suppose webprogramminghub.in has multiple sub domain then it will like, tech.webprogramminghub.in, techworld.webprogramminghub.in and I want these cookies to set by main domain can be easily accessible to all of my subdomain then I need to set the main domain which is webprogramminghub.in.

Secure :– It is another optional field. It specifies that cookie should be transmitted over a secure HTTPS connection. By default, secure option is FALSE. If it is TRUE that means a cookie will only be set if a secure connection exists.

Develop Cookie in PHP

/* Create cookie with setcookie method. */

setcookie("firstcookie","webprogramminghub");

Cookie is created with the name of firstcookie and the value is webprogramminghub. Cookie can only store string values. To convert array value for the cookie after that you need to first convert then into strings.

Cookies for 30 days :-

You need to mention the time to set this cookie. It will remain for 30 days, even if I close my browser.

Set the cookie for multiple subdomains :-

setcookie("firstcookie","webprogramminghub",time()+3600*24*30,"/",".webprogramminghub.in");

Read the Value of Cookie :-

In PHP $_COOKIE is used to read the value of cookie. If one want to read the value of firstcookie (name of the cookie).

$value = $_COOKIE['firstcookie'];

echo $values;   // It echo webprogramminghub

Delete a Cookie :-

To delete a cookie, set the negative time

 setcookie ("firstcookie","webprogramminghub",time()-3600*24);

It will update my first cookie with the given negative time so, it will expire automatically.

0 comments:

Post a Comment