Cookies basically give the website owner the opportunity to store some information on a user’s computer which they can then retrieve at a later stage. Cookies are text files and can be created and stored on a users computer with the help of a browser [Internet explorer, Mozilla Firefox, Chrome, Apple Safari etc.,].The website can even retrieve information from the cookie it has created and this will be helpful for the website to manipulate multiple things. The cookie can persist on the user’s computer according to the expiry time assigned during its creation, staying there if the browser is closed, the computer is switched off and if the internet connection is changed.
Now how to create a cookie using PHP
$expire=time()+1800; setcookie("user_details", $username, $expire);
Here function time() represents current time and 1800 represents 30 minutes. So the variable $expire is set to 30 minutes from the current time.
We use setcookie() to create a cookie using PHP.
$username is some variable.
Now for retrieving the cookie that has got set.
The above code will display the value of $username and this will stop displaying this value after 30 minutes.
Deleting the cookie
This code will delete the cookie. While deleting the cookie assure that the expiration date is in the past.
You can even check whether the cookie is set or not using the below code
<?php if (isset($_COOKIE["user_details"])) echo "The cookie is set and value is " . $_COOKIE["user_details"] . "!<br />"; else echo "The cookie is not set"; ?>
This is just a simple tutorial on how cookie works on websites.