PHPFront

Home > PHP Tutorials > Cookies
The PHP website created by its users!



Cookies


Cookies are an easy way to store information on a user's computer. You may want to track your user's activity, or use a cookie in conjunction with an authentication script, to "remember" users when they return to your site the next day.

Creating a cookie is very simple, we just use the setcookie() function in php.

<?php
setcookie('cookiename', 'im a cookie', time()+3600);

?>


The above code will create a cookie called 'cookiename', with a value of 'im a cookie'. The last part of the code specifies how long until the cookie expires, which in this case is 1 hour.

:: Note: Cookies are part of the HTTP header, so the setcookie() function must be called before any ouput is sent to the browser!

Fetching and echo'ing a cookie is as simple as creating one.

<?php
echo $_COOKIE['cookiename'];

?>


That will print the value of our cookie... 'im a cookie'.

You can also check if the cookie exists...

<?php

if($_COOKIE['cookiename']){
//the cookie exists!
}
else{
//our cookie was not found
}
?>


To delete a cookie, we just set the expiration date in the past. In the code below we will set the expiration date to -1 hour. Which destroys our cookie.


<?php
setcookie('cookiename', 'im a cookie', time() - 3600);
?>