PHP Cookies


Cookies hold information on a local computer instead of on the web server, these are generally used to store login information such as usernames and password.

Remember to include ob_start(); at the top of each page you use cookies on!



How to set a cookie:
PHP Code
  1. <?php
  2. ob_start();
  3. $cookievalue = "some value to be stored";
  4. setcookie("COOKIENAME", $cookievalue, time()+600, "/");
  5. ?>


The $cookievalue variable is the data which we will save to the cookie we are going to create.
setcookies is the PHP function to set a cookie (funnily enough).
The first parameter we have defined as "COOKIENAME" which is what we are going the name this cookie.
The next parameter is for the value of the cookie, we are going to use the variable we previously defined.
The next parameter is for when the cookie will expire in seconds. 600 seconds is 10 minutes, 3600 seconds being 1 hour, etc..



Now we know how to set a cookie let's find out how to display it on the page.

Displaying the value of a cookie:
PHP Code
  1. <?php
  2. ob_start();
  3. echo $_COOKIE["COOKIENAME"];
  4. ?>


echo is to display the value on the page.
Then we tell the code that we want to display a cookie using $_COOKIE to get all the cookies set by the site.
Then we tell what cookie we are looking for in this place it is "COOKIENAME" which you will change to fit your cookie.



Now the last thing we need to know is to learn how to delete a cookie.

Deleting a cookie:
PHP Code
  1. <?php
  2. ob_start();
  3. setcookie("COOKIENAME", "", time()-600, "/");
  4. ?>

setcookie is the PHP function to set a cookie.
The first parameter again is "COOKIENAME" which is the name of the cookie we want to delete.
The next parameter is the value value, we have set this to a blank value as we want to remove the cookie.
The last parameter we will set is the expiry time, as we want to delete this cookie we will make it expire 10 minutes.
DanielXP's Avatar
Author:
Views:
2,797
Rating:
There are currently no comments for this tutorial, login or register to leave one.