How to Use Cookies in PHP: An HTTP cookie is small text file that lets you store website data on user’s computer. When user browsing website than user data will store on his computer browser. HTTP cookies also called browser cookies, web cookie or internet cookie.
What Web Cookies Do:
Main use of storing cookies is to identify the user. When user visit particular website than his information store as text file and on again visit that website, browser send that cookie to the server.
Stored cookies data can be retrieved and used for various purpose. Like items added in the shopping cart, user’s name, password, address and credit card information etc.
Set Cookie in PHP:
In PHP we can create cookie using setcookie() function. This function have 6 argument.
setcookie(name, value, expire, path, domain, secure);
name : The name of the cookie
value : The value of the cookie, which you want to store.
expires : The expiry date, after this set time cookie will vanish. By default its value is 0.
path : The path of the server where cookie will be available. Set value /’ than cookie available within the entire domain. If you set /myfolder/’ than cookie available with myfolder and its sub-directories.
domain : Domain name where cookie is available.
secure : This indicate that the cookie sent only for https connection
1 2 3 4 5 6 |
<?php $cookie_val = 'Harish'; //variable setcookie("username", $cookie_val, time()+3600, '/', 'codefixup.com', true, true); ?> |
Note : setcookie() all parameter except the ‘name’ are optional.
Get Cookies Data :
You can get cookies data through super-global PHP variable called $_COOKIE. It is a associative array that contain all cookies value sent by the browser. This variable stored set cookie data in the ‘name’ parameter.
Check below code to get cookie data.
1 2 3 4 5 6 7 8 |
<?php if(isset($_COOKIE['username'])) //check cookie exist { echo 'Your browser is ' . $_COOKIE['username']; } ?> |
Delete a Cookie data:
If you specific expires argument value than browser cookie data will expire in that time. But if you want to delete cookie data before that specific time than you can use below code. In this expiration time set which will overwrite the previous set expires time.
1 2 3 4 5 6 |
<?php setcookie("username", "", time()-3600); //expiration time set to one hour ago ?> |
Update the Cookie:
To update the cookie data you need to set it again using setcookie() method. This will overwrite the previously saved cookie data.
1 2 3 4 5 6 |
<?php $cookie_value = 'test user'; setcookie('username', $cookie_value, time()+3600, '/'); ?> |
These are method which you can use to manage cookie data. We hope this tutorial will help to use cookies in PHP.