How to use Cookies using PHP

Post Reply
Tony
Lieutenant
Lieutenant
Posts: 86
Joined: Tue Jul 21, 2009 4:11 pm

How to use Cookies using PHP

Post by Tony » Sun Nov 29, 2009 4:52 am

This script shows an example of how to use a cookie. It reads and sets a cookie value that can be used to track visits by a specific individual (PC/browser). The parameters are:
  • The variable name
  • The variable value
  • The length of time the cookie should be saved on the PC for reuse (the example shows 180 days)
  • The domain path for which the cookie is available - for the whole domain use /
  • The domain name
Note the . in front of the domain name in the last parmameter. That means use the cookie for any subdomain of the domain name (like www. or anything else, or nothing).

Code: Select all

<?php 
$cookieCount = 0; 
if (isset($_COOKIE['visitcount'])) $cookieCount = $_COOKIE['visitcount']; 
$cookieCount++; 
setcookie("visitcount",$cookieCount,time()+60*60*24*180,'/','.yourdomain.com'); 
if ($cookieCount > 1) echo "Welcome back. You have been here $cookieCount times."; 
?>
Post Reply

Return to “PHP & MySQL”