PHP cookie tutorial with sample program

Cookie is a variable stored in the user computer. Its a mechanism to store the data for future use. Cookies are part of HTTP header and will passed to the server when the site is accessing in browser.
We can use cookies for knowing the return visitors or for storing a value in user computer. In PHP cookie is create using setcookie() function. And this function should be called in your PHP program before any output is sent to the user computer browser .
We can store multiple values in a single cookie by declare the cookie as an array ( using [] with cookie variable name ).
Here is the syntax for creating a cookie
setcookie (name, value, expiration time , path to store , domain name);

Consider a case. In our website there is a form to enter user’s name. And we need to store that name in his computer for next 30 days.
Now we need to plan a cookie name for this, and we decided to put the name as “user_name”.
Now this will be the sample PHP program to set a cookie in user computer

<?php
$name="syam";
$expire_time=time()+60*60*24*30;
setcookie("user_name", $name, $expire_time);
?>

Here for storing next 30 days, current time + time in seconds for next 30 days will store , ie time()+60*60*24*30.
And dont forget to put this setcookie() in top of your page , better to put before your HTML tags itself.

OK. Now we have stored a cookie. Next time we want to retrieve that cookie value in our website. See the sample program here for retrieving our stored cookie user_name.

<?php
echo $_COOKIE["user_name"];
?>

And its will output
syam

Its always better to check if cookie is set or not before doing any operation with that. See the code below for checking that.

<?php
if (isset($_COOKIE["user_name"]))
echo "Welcome back " . $_COOKIE["user_name"];
else
echo "Welcome guest";
?>

This code will check first cookie is exist or not in that machine. If exist it will do the next operations. Here it will output like “Welcome back syam” because we have already set a cookie for this name.

For Deleting a cookie , we need to change the expiration time to a past time. See the code

<?php
setcookie("user_name", "", time()-3600);
?>

Here this code will set the expiration to a past time one hour less than the current time.

Exit mobile version