Using Cookies With PHP

Store Website Visitor Information With Cookies

businesswoman working at laptop
Blend Images - JGI/Jamie Grill/Brand X Pictures/Gettty Images

As a website developer, you can use PHP to set cookies that contain information about the visitors to your website. Cookies store information about a site visitor on the visitor's computer to be accessed upon a return visit. One common use of cookies is to store a username and password so the user doesn't need to log in each time he visits your website. Cookies can also store other information such as the user's name, the date of the last visit and shopping cart contents.

Although cookies have been around for years and most people have them enabled, there are some users who do not. Cookies can be removed by a user at any time, so don't use them to store anything important.

How to Set a Cookie Using PHP

In PHP, the setcookie() function—which is sent along with the other HTTP headers—defines a cookie.

A cookie follows the syntax setcookie(name, value, expiration) where value is the information stored on the user's computer. Don't put any secure information in value.  For example:

 <?php 
 $Month = 2592000 + time(); 
 //this adds 30 days to the current time 
 setcookie(AboutVisit, date("F jS - g:i a"), $Month);
 ?> 

The example code sets a cookie named "AboutVisit" in the visitor's browser. The cookie sets the value to the current date, and sets the expiration to be in 30 days (2592000 = 60 seconds * 60 mins * 24 hours * 30 days.)

Cookies must be sent before any HTML is sent to the page or they do not work.

The setcookie() function must appear before the <html> tag.

How to Retrieve a Cookie using PHP

In order to retrieve a cookie from the user's computer upon the next visit, follow this example code:

 <?php 
 if(isset($_COOKIE['AboutVisit']))
 { 
 $last = $_COOKIE['AboutVisit']; 
 echo "Welcome back! <br> You last visited on ". $last; 
 } 
 else 
 { 
 echo "Welcome to our site!"; 
 } 
 ?>

This code first checks if the cookie exists. If it does, it welcomes the user back and announces when the user last visited. If the user is new, it prints a generic welcome message.

TIP: If you are calling a cookie on the same page you plan to set one, be sure you retrieve it first before you overwrite it.

How to Destroy a Cookie

To destroy a cookie, use setcookie again, only set the expiration date to be in the past. Here is an example:

 <?php 
 $past = time() - 10; 
 //this makes the time 10 seconds ago 
 setcookie(AboutVisit, date("F jS - g:i a"), $past);
 ?>