4

I run a Drupal 7 site (currently 7.15) since longer time and have the problem with cookies:

I need 2 cookies for non-Drupal PHP-scripts at my web site.

I set them in the hook_init of my custom module:

/**
 * Implements hook_user_login().
 */
function pref_user_login(&$edit, $account) {
    if ($account->uid <= 0) {
      return;
    }

    #drupal_set_message('<p>Hello, '.$account->name.'</p>');
    $auth  = md5(join('_', array($account->uid, MY_SECRET)));
    $year  = time() + 60 * 60 * 24 * 30 * 12;
    setcookie('pref_id', $account->uid, $year, '/', '.preferans.de');
    setcookie('pref_auth', $auth, $year, '/', '.preferans.de');
}

The problem is, that I need to set the both cookies each time a logged in user visits the front page and not just when the user logs in.

Does anybody please have an idea how to do it, maybe by JavaScript if I can't do it regular way?

11

You could do this in hook_preprocess_page() and instead of setting a variable, you could do something like this:

function pref_preprocess_page(&$vars) {
  global $user;

  // whatever other preprocess stuff you want to do here

  if ($user->uid && drupal_is_front_page()) { 
    $auth  = md5(join('_', array($user->uid, MY_SECRET)));
    $year  = time() + 60 * 60 * 24 * 30 * 12;
    setcookie('pref_id', $account->uid, $year, '/', '.preferans.de');
    setcookie('pref_auth', $auth, $year, '/', '.preferans.de');
  }

}
  • I've finally tried your suggestion and unfortunately the $account->uid is empty. And I need the uid for my cookie. Any suggestions please? – Alexander Farber Jun 20 '12 at 17:31
  • 1
    oops...cut and paste error. I've edited the answer :) And added logic so it only does this for logged in users. – Jimajamma Jun 21 '12 at 14:03
  • This works in fact. Thank you for revisiting my question – Alexander Farber Jun 22 '12 at 8:39
  • You might have to clear the Drupal cache before you see new preprocess_page hooks working... – Ray Hulha Jun 28 '13 at 10:13

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.