PHP cookie example

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.

How to Create a Cookie?

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

Note: The setcookie() function must appear BEFORE the <html> tag.


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

PHP has a function setcookie since version 3.0, but this function is too low-level for simple usage.

Function ae_put_cookie below, sets cookie for current domain (removing ‘www’ subdomain to ensure that cookie will be accessible to top-level domain):

source code: php
function ae_put_cookie($name, $value, $days=0)
    $cookie_host = preg_replace('|^www\.(.*)$|', '.\1', $_SERVER['HTTP_HOST']);

    if (substr(strval($days), 0, 1) == 'f')
        $exp = 2147483640;
    else if (substr(strval($days), 0, 1) == 'r')
        $exp = 1; $value = '';
    else if ($days != 0)
        $exp = time() + intval($days)*86400;
        $exp = 0;

    setcookie($name, $value, $exp, '/', $cookie_host);

This first and second argument is this function is name and value of cookie, passed directly to setcookie function. Third argument may have one of the following values:

  • argument not specified (or zero): the cookie will be set as session cookie, so it will expire when user closes web-browser
  • positive integer: number of days before cookie will expire. If today is 5th of September and third parameter equals to 10, cookie will expire at 15th of September.
  • any string beginning with ‘f’, like word ‘forever’ — cookie will stay at user’s browser forever (~ till 2038 year)
  • any string beginning with ‘r’, like word ‘remove’ — cookie will be removed

Here is an example, ‘Cookie Notepad’ which allows to store entered text as a cookie and edit it later:

source code: php
error_reporting(E_ALL); // high level of error reporting

// copy-paste function ae_put_cookie here from above 

if (strtolower($_SERVER['REQUEST_METHOD']) == 'post')
    if (isset($_POST['notepad']))
        $days = isset($_POST['days'])?$_POST['days']:'';
        ae_put_cookie('notepad', $_POST['notepad'], $days);
        header("Location: http://{$_SERVER['HTTP_HOST']}{$_SERVER['PHP_SELF']}");

if (!isset($_COOKIE['notepad']))
    echo "<b>Cookie for notepad is not set</b><br>";

<form action="<?=$_SERVER['PHP_SELF']?>" method="post">
<textarea rows="10" cols="60" name="notepad">
if (isset($_COOKIE['notepad']))
    // escape HTML tags and entities
    $s = str_replace('&', '&amp;', $_COOKIE['notepad']);
    $s = str_replace('<', '&lt;', $s);
    $s = str_replace('>', '&gt;', $s);
    echo $s;
Third argument for ae_put_cookie:<br>
<input type="text" name="days" size="10"><br>
(empty - session cookie, 'f' - forever, 'r' - remove, integer &gt; 0 - number of days in future)
<input type="submit" value="create/save">
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: