Access Cookies with Tokens in Drupal 7

The Token module supports $_GET, so that [current-page:query:?] returns the query string value of a given parameter. The module doesn't support $_COOKIE, however. There are valid security concerns for not supporting $_COOKIE, but what if you want access cookies through tokens anyway?

Create a Custom Cookie

In this example, we'll create a custom module called 'token_cookie'.

The first step is use hook_token_info() to declare the token:

<?php
/**
* Implements hook_token_info().
*/
function token_cookie_token_info() {
 
$info['tokens']['current-page']['cookie'] = array(
   
'name' => t('Cookie value'),
   
'description' => t('The value of a specific cookie of the current page.'),
   
'dynamic' => TRUE,
  );
  return
$info;
}
?>

The next step is to use hook_tokens() to process the tokens:

<?php
/**
* Implements hook_tokens().
*/
function token_cookie_tokens($type, $tokens, $data = array(), $options = array()) {
 
$replacements = array();

 
// Current page tokens.
 
if ($type == 'current-page') {
   
// [current-page:cookie] dynamic tokens.
   
if ($query_tokens = token_find_with_prefix($tokens, 'cookie')) {
      foreach (
$query_tokens as $name => $original) {
        if (isset(
$_COOKIE[$name])) {
         
$replacements[$original] = check_plain($_COOKIE[$name]);
        }
      }
    }
  }
  return
$replacements
}
?>

Now, if you use [current_page:cookie:example-cookie], the rendered markup will be the value of a cookie named 'example-cookie'.

Note: In Drupal 8, you'll still use hook_token_info() and hook_tokens(). The code above might need to be tweaked some, however.

Add new comment