PHP cookie example

cdl_capture_2011-06-23-25_ 000

abstract

This article contains handful PHP function ae_put_cookie for easy cookie setting and "Cookie Notepad" example which allow visitor to store text in his own browser cookie.

compatible

  • PHP 4.1.0 or newer
  • Cookie is a parcel of text sent by a web-server to a web-browser and then sent back unchanged by the browser each time it accesses that server. (– Wikipedia definition)

    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

    <?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;
        else
            $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

    <?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']}");
        }
    }

    ?>
    <html><head><title>CookieNotepad</title></head>
    <body>
    <?php
    if (!isset($_COOKIE['notepad']))
        echo "<b>Cookie for notepad is not set</b><br>";
    ?>

    <form action="<?=$_SERVER['PHP_SELF']?>" method="post">
    Text:<br>
    <textarea rows="10" cols="60" name="notepad">
    <?php
    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;
    }
    ?></textarea>
    <br>
    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)
    <br><br>
    <input type="submit" value="create/save">
    </form>
    </body>
    </html>

    tested

  • PHP 5.1.4 :: Microsoft Internet Explorer 6.0
  • PHP 4.4.2 :: Firefox 1.5
  •  

    http://www.anyexample.com/programming/php/php_cookie_example.xml

    Leave a comment