Restricting Access by IP Address

We had a client who wanted the ability to restrict the view of specific node types to on-campus IP addresses. We decided to do a 301 redirect away from the restricted pages whenever the IP address was not within a given range. We added a field for folks to select whether or not a particular node should be restricted when the content was edited or created. While this may not be the absolute best way to do so, time was short and it worked. :)

You will need to have CCK installed.

First, I added a field called 'field_restricted' to the node type. It was just a single on/off checkbox with two allowed values:
open
Restricted

Next, create a page for the redirect to go to. In my case, I just created a generic page and gave it the URL path 'restricted'.

Then, I created a node type-specific node template called node-story.tpl.php

I included the following code at the top:

<?php
if ($page) {
if ($field_restricted[0]['value'] == 'Restricted') {
$fromip = 'xxx.xxx.xxx.xxx';
$toip = 'xxx.xxx.xxx.xxx';

$ip = ip2long($_SERVER['REMOTE_ADDR']);
if ($ip >= ip2long($fromip) && $ip <= ip2long($toip)) {
// Allowed IP Address
}
else {
drupal_goto('restricted', NULL, NULL, 301);
}
}
}
?>

This first checks to see if this is a full page display. (We wanted the teasers on the front page to be visible to all visitors.) Then, if it is a full page display, check to see if the node is flagged as restricted. If it is, check to see if the visitor's IP address is in the allowed range. If it isn't, use drupal_goto() to redirect the visitor to the restricted page message.