webadmin's picture

PHP Cookies Code Snippet

Coding

If we need to keep track of something variables and it needs to work with the user not logged in ( anonymouse ), what you want to do is use a cookie to keep track on it. You can not use the session to store variables for anonymous visitors in Drupal, because it is tied to the user object, so cookies is one way.

You start off using setcookie( name, value, expire ) - assume that we want to call this value variables_value, and we will use a test value of ' 40123 ', which is a zip code example - We don't want it to expire for six months, so we would want to call in snippet code like this :

setcookie('variables_value', '40123 ', time() + 3600 * 24 * 180);

That time there represents approximately six months worth of seconds being added to the time right now.

3600 is second
24 is hours a day
180 is 30 days X 6 month

Getting the cookie afterwards is even easier - just use $_COOKIE['variables_value'], and it will return the value. So, we could just use this code:

<?php
function saveSerch($search_term) {
setcookie('variables_value', $search_term, time + 3600 * 24 * 180);
}

function readSearch() {
return $_COOKIE['variables_value'];
}
?>

If you're having trouble getting your client-side cookies to stick in Drupal, try using the optional parameter for path.

example:

setcookie('myCookieName', 'myCookieData', 0, '/');

Then, on the next page load output your cookies to the screen. You should see your cookie in the output.

print_r($_COOKIE);

-or more specifically-

print $_COOKIE['myCookieName'];

in drupal 6 we can add cookies code sample for call themes in example, put this on template.tpl.php as a function :

function get_at_styles() {
$scheme = theme_get_setting('style_schemes');
if (!$scheme) {
$scheme = 'style-default.css';
}
if (isset($_COOKIE["atstyles"])) {
$scheme = $_COOKIE["atstyles"];
}
return $scheme;
}