Forgot Password / Register
Site Statistics
Total Members: 510
Total Tutorials: 242
Newsest User: Hp
Todays Unique Hits: 123
0 Users 4 Guests Online

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.

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

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


The $cookievalue variable is the data which we will save to the cookie we are going to create.
setcookies is the PHP funtion 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:
1
2
3
4
<?php
ob_start();
echo $_COOKIE["COOKIENAME"];
?>


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:
1
2
3
4
<?php
ob_start();
setcookie("COOKIENAME", "", time()-600);
?>

setcookies is the PHP funtion 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
Author:
Views:
1978
Rating:
There are currently no comments for this tutorial.