Hello Friends !!
Today i will show you hiw to use Cookie in PHP.
First of all Cookies are small pieces of text, stored by a user’s web browser, that contain the user’s settings, shopping cart contents, or other data used by websites.
In PHP we can set cookies by inbuilt function setcookie().
It is very easy to use and understand. First parameter is the name of the cookie and second one is the value you want to store in cookie.
By above code you can set simple cookie and this cookie will be deleted when user close their browser.
We can also set the time how long we want the cookie.
setcookie(‘username’, $name, $cookie_life);
Above example create cookie for 1 year. Yes 31536000 seconds means 1 year.Remember, cookies must be deleted with the same parameters they were set with.If users clear their history from browser then cookies will be deleted.
We can also use a forth parameter, the fourth parameter is the cookie path.
$path = ‘/folder/’;
setcookie(‘username’, $name, $cookie_life, $path);
The fourth parameter defines a path from which the cookie can be accessed. In the above example only scripts inside /folder/ will be able to access the cookie ($username), in scripts outside this folder the cookie will be unavailable.
Thereâ€™s also a fifth parameter, the fifth parameter defines a hostname that can retrieve the cookie.
$path = ‘/folder/’;
$hostname = ‘your host address’;
setcookie(‘username’, $name, $cookie_life, $path, $hostname);
The fifth parameter is the domain which can retrieve this cookie. Normally a cookie can only be accessed by the domain that set it, otherwise sites would be able to get private information from cookies set by other sites. With this parameter we can define another domain which can retrieve the cookie we are setting.
Click on below links for more:
Now How to Retrive Cookie ?
Once you have set a cookie on a user’s system, it is only avialable when they load the next page. The cookie can be accessed very easily:
// or $_COOKIE[‘username’]
When the cookie is set the value is automatically URL encoded, when the script retrieves a cookie, it automatically decodes the value, so you don’t have to worry about that.
Always remember, a limitation of cookies is that you have to set it before you can send the HTTP headers. In other words, always do all your cookie setting BEFORE you output any HTML, otherwise the cookie will not be set and your page will have an ugly error stuck on it.