Set Cookies Get Cookies Delete Cookies with PHP
Cookies are small files created by server on a user computer, cookies are primarily used to store little information about anything, and when user visits your website next time the information stored in cookies can be retrieved and used in various purpose.Uses of cookies
Cookies can be used for various purpose such as:- Store user preferences (color, font size, element size, theme etc.)
- Track progress (page number, percentage, etc.)
- Store username or numbers (to identify user)
Set Cookie
We can create a cookie on a user computer using PHP setcookie(). This function requires commonly 3 parameter to create a cookie, name, value and expiration time.PHP
12
$cookie_val = 'Chrome'; //variable
setcookie("browser", $cookie_val, time()+3600); //cookie name, value & time (1 hour)
PHP
12
$cookie_val = 'Chrome'; //variable
setcookie("browser", $cookie_val, time()+3600, '/', 'sanwebe.com', true, true);
Retrieve Cookie Value
Once the cookies have been created, we can simply retrieve the value of our cookie from any page with predefined PHP variable called $_COOKIE. The code below displays the value of the cookie on the browser.echo 'Your browser is ' . $_COOKIE['browser'];
The code above will end up with an error, if it doesn’t find cookie named “browser”, therefore it’s a good idea to check whether cookie exist or not before trying to output its value.
PHP
1234
if(isset($_COOKIE['browser'])) //check cookie exist
{
echo 'Your browser is ' . $_COOKIE['browser'];
}
PHP
12
$cookie_value = (isset($_COOKIE['browser']))? $_COOKIE['browser'] :'no cookie';
echo $cookie_value ;
Delete a Cookie
It is fairly easy to delete a cookie stored in your computer. We just have to set expiration date to the past :
setcookie("browser", "", time()-3600); //expiration time set to one hour ago
When you execute this code, it will overwrite the expiration time of cookie named “browser” to one hour ago, which will trigger the removal mechanism in your browser causing this particular cookie to be removed instantly from the browser.