Sunday, 29 September 2013

Introduction and use of cookies in PHP

Introduction

A cookie is a small text file composed of alphanumeric characters, which is created on your computer when your browser accesses a website that uses cookies. The files are used to help your browser navigate the website and fully use all its features like logins, preferences, language settings, themes, among other common features. The cookie is used solely to help your browser process a website, it doesn't collect any information from your computer or your file system.

The cookie containing following things
  • The name of the website server that created the cookie
  • The duration of the cookie-how long use the cookie will be alive.
  • A cookie value-this unique information is normally a randomly generated number.

HTTP (Hyper Text Transfer Protocol), is  protocol used by the WWW ( World Wide Web). HTTP  is responsible for submit the user request to the Web server and receive the response from the server.
It is a  stateless protocol means it does not store or remember any value after sending the request  or receiving the response from server.
So cookies are used to remember some useful date in client side for example to remember login username and password in client side.

Using cookies in PHP

To create a cookie, use setcookie() function in php

setcookie(cookiename, value, [expire]);
setcookie("cook","27");

Expiration—expressed using time. If not set, cookie is valid for this user session only.

setcookie(cookiename, value, [expire]);
setcookie("other","1", time()+60*60*24*30);

Retrieved similar to $_POST variables: $_COOKIE['cookiename']

Deleting and checking cookies

To delete: overwrite cookie with expiration time in the past.

setcookie("cook","",time()-100);

Actual cookie deletion done by user's browser.

To see if the user accepts cookies, write one and then check (on another page or after a refresh) to see if it exists.

No comments:

Post a Comment