PHP Script / Javascript – Detect and run by Country

When faced with the challenge of including a javascript only for Internet connections from the US I discovered that javascript is unable to detect IP addresses (and as a consequence the location of the user).

As a work around you can use the GEO plugin to detect the Country, and if it meets the criteria include the javascript.

This is done using Geo Plugin (http://www.geoplugin.com), PHP and your javascript.

geoio-logo

The example below detects the REMOTE ADDRESS and if it is from the US includes to SOPA redirect javascript code.

(Yes – I only intend to blackout MOCKBOX.NET for US Internet sources – this is your problem and I do not intend on inflicting punishment on other users)

To use, simply copy into the header of your valid PHP parse file (template HTML file).

<?php

$geoplugin = unserialize( file_get_contents(‘http://www.geoplugin.net/php.gp?ip=’ . $_SERVER[‘REMOTE_ADDR’]) );

if ( is_numeric($geoplugin[‘geoplugin_latitude’]) && is_numeric($geoplugin[‘geoplugin_longitude’]) ) {

    $lat = $geoplugin[‘geoplugin_latitude’];
    $long = $geoplugin[‘geoplugin_longitude’];

if ($geoplugin[‘geoplugin_countryCode’] == ‘US’) {

echo ‘<script>var a=new Date;if(18==a.getDate()&&0==a.getMonth()&&2012==a.getFullYear())window.location=”http://sopastrike.com/strike”;</script>’;                                                                       }
  }
     
?>