A cookie is a flat file that stores tiny bits of information. It is stored on the client’s machine and is passed to the client when they visit your site. Each cookie can store anything from usernames to number of visits to a site. This tutorial will teach you how to create, retrieve, display, and delete cookies using php
1. Create a Cookie using PHP

Cookies are created using the setcookie() function. Below is an example of the setcookie() function
setcookie($name, $value, $expired, $path, $domain, $secure)
There are values that you can pass into the setcookie() function. The values are: name of the cookie, value of the cookie, the date the cookie expires, path where the cookie is available on the server, domain where the cookie is available, and where it is coming from a secure page.
The three values that we are worried about are $name, $value, and $expired.
Below is the php code to create a php cookie named "username". We set the value of the cookie to "Tom", and set the expiration date at one hour from now.
<?php
setcookie("username", "Tom", time()+3600);
?>
The cookie is set through the browser once a client visits your site or page that you set the cookie on.

2. Retrieve & Display a Cookie using PHP

Now let’s retrieve & display the cookie we just set. We retrieve the cookie using the predefined $_COOKIE array. Then we display the cookie using the echo function. Here is the code that will get you the cookie.
<?php
echo $_COOKIE["username"];
//http://www.infysolutions.com
?>
3. Delete a cookie using PHP
We can delete the cookie when we are finished with it. Cookies are deleted by simply setting the expiration date to a past date. The example below will delete the cookie named username.
<?php
setcookie("username", "Tom", time()-(60*60*24*365));
?>
That’s it! You have just created a cookie on the client’s machine, retrieved & displayed the cookie and deleted the cookie once you were done with it.

Recommended Answers

All 2 Replies

Although cookies are useful for long-term storage, I find that people can so easily disable them making your site not work. That is why I have invented what I call server-side cookies. These are cookies all stored within a mysql database and a retrieved by the users ip address. To help extend this topic I shall post the code for server-side cookies and explain how to use them. First you will need to create the mysql database which can be done just by configuring and running/executing the following code.

<?
$dbhost='localhost'; //database host (usually localhost)
$accountname='root'; //database username.
$password=''; //database password
$database='my_database'; //database name - not table
 
//configure the above variables.
 
 
$linkID = @mysql_connect($dbhost,$accountname,$password)
	or die("Could not connect to MySQL server");
@mysql_select_db($database) or die("Could not select database");

mysql_query('CREATE TABLE `'.$database.'`.`cookies` (`name` TEXT NOT NULL, `value` TEXT NOT NULL, 
`ip` TEXT NOT NULL, `expires` TEXT NOT NULL) ENGINE = MyISAM') or die(mysql_error());
echo "Table named 'cookies' has been created successfully."
?>

So after configuring the mysql variables at the top of that code and running/executing that code, you then may delete the file containing the above code. Then next is to add the functions to be able to use server-side cookies. So place the following code near the top of the page.

$dbhost='localhost';
$accountname='root';
$password='';
$database='my_database';

$linkID = @mysql_connect($dbhost,$accountname,$password)
	or die("Could not connect to MySQL server");
@mysql_select_db($database) or die("Could not select database");

function ssl_cookie_make($cookies_minutes_till_expire,$cookies_houres_till_expire,$cookies_days_till_expire,$cookiename,$cookievalue)
    {
    $cookiename=str_replace("'",'"',$cookiename);
    $cookies_months_till_expire=0;
    $cookieexpiresy=date(Y);
    $cookieexpiresm=date(m)+$cookies_months_till_expire;
    $cookieexpiresj=date(j)+$cookies_days_till_expire;
    $cookieexpiresg=date(G)+$cookies_houres_till_expire;
    $cookieexpiresi=date(i)+$cookies_minutes_till_expire;
    if ($cookieexpiresi>59)
        {
        while ($cookieexpiresi>59)
            {
            $cookieexpiresg+=1;
            $cookieexpiresi-=60;
            }
        }
    if ($cookieexpiresg>24)
        {
        while ($cookieexpiresg>24)
            {
            $cookieexpiresj+=1;
            $cookieexpiresg-=24;
            }
        }
    if ($cookieexpiresj>30)
        {
        while ($cookieexpiresj>30)
            {
            $cookieexpiresm+=1;
            $cookieexpiresj-=31;
            }
        }
    if ($conkieexpiresm>12)
        {
        while ($cookieexpiresm>12)
            {
            $cookieexpiresy+=1;
            $cookieexpiresm-=12;
            }
        }
    mysql_query("INSERT INTO `cookies` SET `name`='".$cookiename."', `value`='".$cookievalue."', `ip`='".gethostbyaddr($_SERVER['REMOTE_ADDR'])."', 
`expires`='".$cookieexpiresy.",".$cookieexpiresm.",".$cookieexpiresj.",".$cookieexpiresg.",".$cookieexpiresi."'");
    }
 
function ssl_cookie_value($cookiename)
    {
    $cookiename=str_replace("'",'"',$cookiename);
    $cookiesql=mysql_query("SELECT * FROM `cookies`");
    $cookiedateexplode=explode(',',date(Y.','.m.','.j.','.G.','.i));
    while ($cookierow=mysql_fetch_array($cookiesql))
        {
        $cookiesqlexplode=explode(',',$cookierow['expires']);
        if ($cookiesqlexplode[0]<=$cookiedateexplode[0] && $cookiesqlexplode[1]<=$cookiedateexplode[1] && $cookiesqlexplode[2]<=$cookiedateexplode[2] 
        && $cookiesqlexplode[3]<=$cookiedateexplode[3] && $cookiesqlexplode[4]<=$cookiedateexplode[4])
            {
            mysql_query("DELETE FROM `cookies` WHERE `expires`='".$cookierow['expires']."'");
            // AND `ip`='".$cookierow['ip']."' AND `name`='".$cookierow['name']."' AND `value`='".$cookierow['value']."'
            }
        unset($cookiesqlexplode);
        }
    unset($cookiedateexplode);
    
    $cookieresult=mysql_query("SELECT `value` FROM `cookies` WHERE `ip`='".gethostbyaddr($_SERVER['REMOTE_ADDR'])."' AND `name`='".$cookiename."'");
    $cookierow=mysql_fetch_array($cookieresult);
    return $cookierow['value'];
    }
    
function ssl_cookie_changevalue($cookiename,$cookienewvalue)
    {
    $cookiename=str_replace("'",'"',$cookiename);
    mysql_query("UPDATE `cookies` SET `value`='".$cookienewvalue."' WHERE `name`='".$cookiename."' AND `ip`='".gethostbyaddr($_SERVER['REMOTE_ADDR'])."'");
    }
    
function ssl_cookie_changeexpire($cookiename,$cookies_minutes_till_expire,$cookies_houres_till_expire,$cookies_days_till_expire)
    {
    $cookiename=str_replace("'",'"',$cookiename);
    $cookies_months_till_expire=0;
    $cookieexpiresy=date(Y);
    $cookieexpiresm=date(m)+$cookies_months_till_expire;
    $cookieexpiresj=date(j)+$cookies_days_till_expire;
    $cookieexpiresg=date(G)+$cookies_houres_till_expire;
    $cookieexpiresi=date(i)+$cookies_minutes_till_expire;
    if ($cookieexpiresi>59)
        {
        while ($cookieexpiresi>59)
            {
            $cookieexpiresg+=1;
            $cookieexpiresi-=60;
            }
        }
    if ($cookieexpiresg>24)
        {
        while ($cookieexpiresg>24)
            {
            $cookieexpiresj+=1;
            $cookieexpiresg-=24;
            }
        }
    if ($cookieexpiresj>30)
        {
        while ($cookieexpiresj>30)
            {
            $cookieexpiresm+=1;
            $cookieexpiresj-=31;
            }
        }
    if ($conkieexpiresm>12)
        {
        while ($cookieexpiresm>12)
            {
            $cookieexpiresy+=1;
            $cookieexpiresm-=12;
            }
        }
    mysql_query("UPDATE `cookies` SET `expires`='".$cookieexpiresy.",".$cookieexpiresm.",".$cookieexpiresj.",".$cookieexpiresg.",".$cookieexpiresi."' 
    WHERE `name`='".$cookiename."' AND `ip`='".gethostbyaddr($_SERVER['REMOTE_ADDR'])."'");
    
    
    $cookiesql=mysql_query("SELECT * FROM `cookies`");
    $cookiedateexplode=explode(',',date(Y.','.m.','.j.','.G.','.i));
    while ($cookierow=mysql_fetch_array($cookiesql))
        {
        $cookiesqlexplode=explode(',',$cookierow['expires']);
        if ($cookiesqlexplode[0]<=$cookiedateexplode[0] && $cookiesqlexplode[1]<=$cookiedateexplode[1] && $cookiesqlexplode[2]<=$cookiedateexplode[2] 
        && $cookiesqlexplode[3]<=$cookiedateexplode[3] && $cookiesqlexplode[4]<=$cookiedateexplode[4])
            {
            mysql_query("DELETE FROM `cookies` WHERE `expires`='".$cookierow['expires']."'");
            // AND `ip`='".$cookierow['ip']."' AND `name`='".$cookierow['name']."' AND `value`='".$cookierow['value']."'
            }
        unset($cookiesqlexplode);
        }
    unset($cookiedateexplode);
    }

Then of course there is using these functions. Below is the code showing the use of each function.

//This function creates a server-side cookie.
//ssl_cookie_make(mins_expire,  houres_expire,  days_expire,  cookie_name,  cookie_value);
ssl_cookie_make(6,0,0,'cookie name','value');
 
//This function returns the value of a cookie for this particular user.
ssl_cookie_value('cookie name');
 
//This function changes the cookie value for this particular user.
ssl_cookie_changevalue('cookie name','new value');
 
//This function changes when the cookie expires for this particular user.
//ssl_cookie_changeexpire(cookie_name,mins_expire,  houres_expire,  days_expire);
ssl_cookie_changeexpire('cookie name',0,-9,0);

As you can see, the above code box explains itself and these cookies can only last for untill the person logs off the internet which is about 1-2 days.

I thought I would share this with everybody and since this topic is about a cookies tutorial this place would suite best.

A lot of people get on the net with IPs that change very often, dial-up, mobile phones, wireless networks, different locations etc. There's are also single IPs that can be used for multiple clients when they are behind a NAT.

Also to consider:

There are client side storage facilities other then cookies that are being standardized and/or implemented.

Examples:
http://www.whatwg.org/specs/web-apps/current-work/#structured-client-side-storage
https://developer.mozilla.org/en/DOM/Storage

Implementation in JS:
http://dojotoolkit.org/node/115

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.