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
- 1
- 2
$cookie_val = 'Chrome'; //variable
setcookie("browser", $cookie_val, time()+3600); //cookie name, value & time (1 hour)
PHP
- 1
- 2
$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.PHP
- 1
echo 'Your browser is ' . $_COOKIE['browser'];
PHP
- 1
- 2
- 3
- 4
if(isset($_COOKIE['browser'])) //check cookie exist
{
echo 'Your browser is ' . $_COOKIE['browser'];
}
PHP
- 1
- 2
$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 :PHP
- 1
setcookie("browser", "", time()-3600); //expiration time set to one hour ago