Home Logo
Show Full Menu
Hide Full Menu


Created: 12/10/10 Views: 2199 myFave Image

In this tutorial we will learn Cookies
In this tutorial we are going to look at cookies. cookies are very similar to sessions, however with a cookie you are able to store it so that it is retrievable on multiple user sessions, meaning that the user can close their browser, shut down, come back to our web page and we will still be able to get the information without using a database.

    4 basic parts for a cookie
  • name this is the name given to the cookie so you can call it at another time
  • value this is the value of that cookie
  • expiration this is how long the cookie is set for before it is deleted
  • path this is where on the site the cookie is available

So why would we really want to use this?
  • To allow the 'remember me?' part of a login form
  • To remember the users username for them
  • To keep a few specific settings for that user
  • To be able to tell the last time the user logged in

    How to create a cookie
  • <?php
  • setcookie("name", "value", expiration_in_seconds, "path");

  • setcookie("user", "benj", time()+(60*24*60*60), "/"); //60 days; 24 hours; 60 mins; 60secs
  • ?>

    Call and Print Cookie
  • <?php
  • print $_COOKIE['name'];

  • print $_COOKIE['user'];
  • ?>

  • benj

    Delete Cookie
  • <?php
  • setcookie("name", "value", expiration_in_seconds, "path");

  • setcookie("user", "benj", time()-3000, "/"); //3000 seconds ago
  • ?>

You should give this a go for yourself, creating a cookie on one page, closing the browser or restarting and then calling it on again as well as finally destroying it.

back to: PHP Extended

There are no comments