Monday 22 April 2013

PHP Cookies


PHP Cookies

A cookie is often used to identify a user.
Cookies have been around for quite some time on the internet.
They were invented to allow webmaster's to store information about the user and their visit on the user's computer.

What is a Cookie?

A cookie is often used to identify a user. A cookie is a small file that the server embeds on the user's computer. Each time the same computer requests a page with a browser, it will send the cookie too. With PHP, you can both create and retrieve cookie values.

creating your first php cookie

When you create a cookie, using the function setcookie, you must specify three arguments. 

These arguments are setcookie(name, value, expiration):

·        name: The name of your cookie. You will use this name to later retrieve your cookie, so don't forget it!

·        value: The value that is stored in your cookie. Common values are username(string) and last visit(date).

·        expiration: The date when the cookie will expire and be deleted. If you do not set this expiration date, then it will be treated as a session cookie and be removed when the browser is restarted.

How to Create a Cookie?


The setcookie() function is used to set a cookie.

Syntax


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

Retrieving your fresh cookie

If your cookie hasn't expired yet, let's retrieve it from the user's PC using the aptly named $_COOKIE associative array. The name of your stored cookie is the key and will let you retrieve your stored cookie value!


PHP Code:

<?php
if(isset($_COOKIE['lastVisit']))
       $visit = $_COOKIE['lastVisit'];
else
       echo "You've got some stale cookies!";

echo "Your last visit was - ". $visit;
?>

This handy script first uses the isset function to be sure that our "lastVisit" cookie still exists on the user's PC, if it does, then the user's last visit is displayed. If the user visited our site on February 28, 2008 it might look something like this:

Display:

Your last visit was - 11:48 - 02/28/08

How to Delete a Cookie?


When deleting a cookie you should assure that the expiration date is in the past.

Delete example:

<?php
// set the expiration date to one hour ago
setcookie("user", "", time()-3600);
?>

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More