Tuesday, August 7, 2012

Read Write Cookie with PHP

Save cookie
(before the body tag, set variables and the save cookie function for page postback)

if(isset($_GET['save_cookie']))
{
   setcookie("event[$id]","$time:$page:$link",time()+(86400*7),'/',$domain);
}

(within the body, use a form to incur post back)
<form class="add" method="get">
<input name="save_cookie" type="hidden" />

<input type="submit" value="+ Add to your day" />

<span class="ic-addtoyourday">Add to your day</span>
</form>

Read cookie
(loop through the cookie array)
    
    foreach ($_COOKIE['event'] as $key => $value)
    {
        //echo "$key:$value";
        $arr = explode(':', $value);
        echo '<a href="'.$arr[2].'">'; // link
        echo $arr[1]; // title
    }
    
    if(!isset($_COOKIE['event']))
    {
        echo 'You have not added any events.';
    }
    

No comments:

Post a Comment