I needed a script that would determine the IP Address of the visitor and display information based on the result. My goal was to create a sort of Intranet for my business website where employees at work would see certain content while normal visitors wouldn’t.
Before I started using MODx I was using a CMS I built myself and built this feature into the core. Here is a modified version I wrote for MODx in snippet form. It checks to see if the IP of the visitor matches a manually set search string.
Current Features:
- Show chunks based on visitor’s IP Address
- Temporary override for IP check using snippet parameter &subnet.
- Show a different chunk on intranet failure
This snippet is in development, please post bug reports here
<?php
/**
* IntraFilter
*
* Shows a chunk based on client's IP address
* This allows for a website to have specific
* for users in a certain subnet.
*
* SET THE DEFAULT SUBNET BELOW !!!
*
* @author Matthew Pietz <[email protected]>
* @version 0.1b
* @since MODx 0.9.5
*/
// Change this to your subnet
$default_subnet = '71.';
// NO MORE CONFIGURATION BELOW THIS LINE
/////////////////////////////////////////////
/**
* Parameters:
* - &chunk - Chunk to show if user is in subnet
* - &else - (optional) Chunk to show otherwise
* - &subnet - Temporary override for subnet checking
*/
$chunk = isset($chunk) ? $chunk : '';
$else = isset($else) ? $else : '';
$subnet = isset($subnet) ? $subnet : $default_subnet;
if (is_numeric($chunk))
$chunk = ($doc=$modx->getDocument(intval($chunk))) ? $doc['content'] : '';
elseif (!empty($chunk))
$chunk = $modx->getChunk($chunk);
else return $_lang['intra_chunk_error'];
if (empty($chunk)) return $_lang['intra_chunk_notexist'];
$elsechk = $modx->getChunk($else);
$inhouse = (preg_match('/^'.preg_quote($subnet).'/', $_SERVER['REMOTE_ADDR']) > 0);
if ($inhouse)
return $chunk;
else return $elsechk;
?>
There’s two language strings that I haven’t set yet. Again, this is a beta test.
The snippet checks the IP Address by comparing it to [tt]$subnet[/tt] from left to right. In other words, the more of the IP address you enter, the more specific your Intranet will be (eg "71." accepts all IP Addresses starting with "71.")
Let me know what you think
NOTE: Be sure to change [tt]$default_subnet[/tt] to whatever you want to define as your ’Intranet’