PHP cookies Quick

4 February 2009| No Comment| Print

Cookies are mainly used to authenticate a users session, they are small packets of data that are stored in the web browser that allow a website to match specific user information to that in the database, thus authenticating the user.

So what are the values?

setcookie($name, $value, $expire, $path, $domain, $secure);
  1. $name – is what you want to call the cookie, we will use this to reference the cookie later
  2. $value – value of the cookie. for example “ashleyford”
  3. $expire – is the time in UNIX timestamp format when the cookie will expire for example, time()+”3600″. The cookie would then expire after an hour.
  4. $path – The path on the server where the cookie will be available. For example, if the path is set to “/”, the cookie will be available through out the whole site. If the cookie is set to say “/account/”, the cookie will only be available under /account/ page and all its sub-directories.
  5. $domain – For example, if the domain is set to “dotdashcreate.com”, the cookie will be available within the domain including all its sub-domains, for example account.dotdashcreate.com.

Its good to note at this point that the cookie must be set before any other HTML code so generate cookies above the headers on your page.

So here’s an example. We have set the cookie with the value of ‘ashleyford’ and it is due to expire in 1 hour.

setcookie("username", "ashleyford", time()+3600);

now we want to read the data and display the username on the page.

echo $_COOKIE["username"];

this will echo: ashleyford


Share:
  • Print
  • Digg
  • del.icio.us
  • Facebook
  • StumbleUpon
  • Google Bookmarks
  • DZone
  • Reddit
  • Netvibes

Leave a comment...

Add your comment below, or trackback from your own site. You can also subscribe to these comments via RSS.

Be nice. Keep it clean. Stay on topic. No spam.

You can use these tags:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

This is a Gravatar-enabled site. To get your own globally-recognized-avatar, register at Gravatar.

Your Ad Here