PHP Cookie

A Cookie can be defined as a thing that is used to store a small amount of data (maximum around 4KB) within the user's browser itself. Later, whenever the user revisits an already visited page, all the data in the cookie is automatically sent to the server within the request.

A very common use of cookie is to store username and password on your computer so that you don't have to login again each time you visit a website. We can make a cookie to last for a fixed amount of time ranging between a few seconds to several years as per our desire. We can even set a cookie to expire once the browser application is closed.

Setting a Cookie

Syntax

setcookie(name, value, expire, path, domain, secure, httponly);

Example

In the following example, setcookie() is used to store the number of pages user views in the his current browser session. Here the expires argument is zero hence the cookie will disappear when the user closes his browser. Further, the domain argument is an empty string meaning the browser will only send the cookie back to the exact web server that created it.

<?php 
setcookie("yourViews", 5, 0, "/", "", false, true );
?> 

Accessing a Cookie

Syntax

echo isset( $_COOKIE[Cookie Name] );

Example

<?php
setcookie( "yourViews", 5, 0, "/", "", false, true );
echo isset( $_COOKIE["yourViews"] );
?> 

This will produce following result

Above example will display nothing in first run as $_COOKIE[ "yourViews" ] doesn t exist. But when the user reloads the page to run the script again, the code will display 1 ( true ) because the browser has sent the yourViews cookie back to the server once hence second time the result will be:

1

Removing a Cookie

Example

<?php
$t=time()-60; //this makes the time 60 seconds ago
setcookie( "visitor", "", $t);
echo "Cookie named visitor is no longer there";
?> 

This will produce following result

In order to remove the cookie, we use setcookie once again, only set the expiration date to be sometime in the past (here 60 seconds). This is done when you 'logout' of a site

Cookie named visitor is no longer there


 
SHARE THIS IF YOU LIKE!
submit to reddit

SUBSCRIBE FOR LATEST UPDATES
HAVE WE CONNECTED ON FACEBOOK?
TOP TUTORIALSTOP CODE EXAMPLESTOP LIVE DEMOLINKSSTAY CONNECTED
HTML Tutorial
HTML5 Tutorial
Bootstrap3 Tutorial
Javascript Tutorial
TypeScript Tutorial
AngularJS Tutorial
CSharp Tutorial
PHP Tutorial
Developer Tools
Javascript
AngularJS
Google MAP API V3
ASP.NET
Javascript
AngularJS
Google MAP API V3
Contact Us
Advertise with Us
Privacy Policy
Disclaimer
Stay connected. We actually like you. If you want to get up to the minute updates, then connect with us on your fav below.
 
Twitter   Linkedin   Facebook   Google+    RSS   Pinterest
 
Protected by Copyscape Original Content Checker
 
 
Copyright ©2017 www.techstrikers.com Unauthorized reproduction/replication of any part of this site is prohibited.