I have to put a limitations on the number of nodes an anonymous user can view. So I have to set a limitations of 5 after that the anonymous user is made to login by redirecting to the login page.

So I have used hook_nodeapi and under view operation i maintains a counter in cookie for the no of times the user visits the node.So if exceeds the counts it redirects to login page. But some how it doent work and gets redirected randomly..i mean not after 5 but after 7,8,,or some number.Some times it doesnt even increments the counter. So is it because the cache is enabled or is there some other reason to it. below is my code used under hook_nodeapi:-

    $m = $_COOKIE['anonymousquizview'];
    setcookie("anonymousquizview", $m, 0,"/", "www.example.com");    
  else {  
    setcookie("anonymousquizview", 1, 0,"/", "www.example.com");}
    if ($_COOKIE['anonymousquizview'] >=5) {
      drupal_set_message("To attend more challenges, kindly login.");

1 Answer 1


If cache is enabled hook_nodeapi() is not always executed. The first time a node is viewed Drupal renders the page and save it in the cache. During this process, hook_nodeapi() will be fired. Next time the same page is viewed, Drupal will find the rendered copy in the cache, serve this copy, and no hook_nodeapi() will be fire fired.

You have to do it in hook_boot. This hook is fired even for cached pages. You must first check if current path is a node path (you may use arg() function). Try to add lightweight code as it will be executed in every page petition.

Remember that this protection is easily bypassed clearing the cookies for your domain.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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