Monday, 18 June 2012

How many types of cookies in php?


There are 2 types of cookies: 
(1) Session Based which expire at the end of the session.
(2) Persistent cookies which are written on harddisk.

    Session cookies expire at the end of the session. This means, 
when you close your browser window, the session cookie is deleted. This 
website only uses session cookies.

    Persistent cookies do not expire at the end of the session.

A session cookie may be created when you visit a site or portion of a
 site. The cookie exists for the duration of your visit. For example, a 
session cookie is created when you use the Personal Login to access 
secured pages. Depending on the settings in your browser, you may have 
the option to deny the session cookie; however, if you deny the cookie 
you may have trouble using the site which relies on that cookie.



PHP provided setcookie() function to set a cookie. This function 
requires upto six arguments and should be called before <html> 
tag. For each cookie this function has to be called separately.
setcookie(name, value, expire, path, domain, security);
<?php
   setcookie("name", "John Watkin", time()+3600, "/","", 0);
   setcookie("age", "36", time()+3600, "/", "",  0);
?>
Here is the detail of all the arguments:

  • Name - This sets the name of the cookie and is stored in an environment variable called HTTP_COOKIE_VARS. This variable is used while accessing cookies.
  • Value -This sets the value of the named variable and is the content that you actually want to store.
  • Expiry - This specify a future time in seconds since 00:00:00 GMT on 1st Jan 1970. After this time cookie will become inaccessible. If this parameter is not set then cookie will automatically expire when the Web Browser is closed.
  • Path -This specifies the directories for which the cookie is valid. A single forward slash character permits the cookie to be valid for all directories.
  • Domain - This can be used to specify the domain name in very large domains and must contain at least two periods to be valid. All cookies are only valid for the host and domain which created them.
  • Security - This can be set to 1 to specify that the cookie should only be sent by secure transmission using HTTPS otherwise set to 0 which mean cookie can be sent by regular HTTP.

No comments:

Post a Comment