We learn more by looking for the answer to a question and not finding it than we do from learning the answer itself.

What are Cookies and How to use them?

What are Cookies ?
Cookies are little files that are stored on a user’s computer by the server. They are usually used to identify a user. When you browse to a site that has stored a cookie again, your web browser also sends the cookie.

They don’t have any essential part of a website but can provide some of the “little things” that can set your website apart from the rest. Cookies are small tidbits of information that you save on the client’s computer so that you can access them next time they visit the website.

Purpose of Using Cookies:

  • Store Username and Password for future access (i.e. The “Remember Me” Check mark that you normally see on the sites
  • Use for keeping track of the users progress (i.e. Check whether the person have already performed a certain action on the website)


How to use Cookies?
Well we will be using php for this purpose to demonstrate it.
1. Setting the Cookies: Setting a cookie requires a key, a value, and the amount of time to allow the cookie to exist.

$value = 'Some Value Here';
setcookie('name',$value, time()+60*60*24*30); //  time()+60*60*24*30 = 30 days


2. Getting the Values of the Cookies: Getting the value of the cookies are very simply, you can easily get them by using the variable name defined.

if(isset($_COOKIE['name']) && $_COOKIE['name']!='')
{
  echo $_COOKIE['name'];
}


They can even be set to specific directories directives, including path, domain using the following piece of code.

setcookie('name',$value,time() + time()+60*60*24*30,'/~foldername/','domain.name',true,true);

This cookie is the same as the code mentioned before, but we’re telling the cookie to be applied towards the directoryname : “~foldername” on the domain : “domain.name”. It is for use only on an SSL connection and it may not be used by JavaScript.


Few things to remember:

  • A user can delete cookies at any time.
  • A user can turn cookies off in their browser.



Hope this small piece of reference information may help you.

Leave a Comment

blog comments powered by Disqus