Cookies are basically small files which are stored in User’s Computer.
Their main purpose is to hold data specific to a particular client and
Website, They can only be accessed either by Web Server or the client
computer. This allows the server to access user specific data while
saving space on the web server, It allows the server to deliver specific
tailored web pages to a particular user.
Cookies act as a mechanism to store data in the remote browser and thus tracking and identifying return users.
A Cookie mainly contains data in (key,value) pairs for example (name,aneesh) , (message,cookies are great).
That’s a lot of theory there now let’s move on how to use cookies using PHP.
Cookies in PHP
PHP provides us a with suite of functions for manipulation of cookies.
Setting of Cookies
These functions include setcookie() or setrawcookie() . As cookies are a part of HTTP headers so , it’s obvious we need to call setcookie() before sending any data.
Accessing Cookies
Any cookies which are sent to the server from the client will be automatically included in $_COOKIE auto – global array.
These cookies can be accessed using following syntax:-
$_COOKIE['name'];
The setcookie() function is used for setting of cookies
Syntax :-
setcookie(name, value, expire, path, domain, secure, httponly);
Example:-
setcookie('name', 'aneesh');
Example involving Expire time:-
$minutes = 20; setcookie('name', 'aneesh' , time()+($minutes*60));
Printing:-
echo $_COOKIE['name'];
Output:-
aneesh
Making a Simple Application in PHP using Cookies
Now that we know quite a lot about what are cookies and how do we use them lets use them and make a small PHP Application.
Visited.php :-
Sample Page Welcome Visitor
According to your browser cookies you have'; } else { echo 'have not'; } ?> visited our site in the last 10 days.
1. When visiting for the first time :-
Welcome Visitor According to your browser cookies you have not visited our site in the last 10 days.
Welcome Visitor According to your browser cookies you have visited our site in the last 10 days.
No comments:
Write comments