Monthly Archives: January 2016

Detecting IPv6 with JS and PHP

0 minutes, 36 seconds

A friend of mine wanted a way to know if visitors to her site were coming from an IPv6 address. To do this, you would run some PHP to output a JS variable with global scope:

// thanks to:
// https://plugins.svn.wordpress.org/ipv6detector
$ip =  $_SERVER['REMOTE_ADDR'];
if (substr_count($ip, ":") > 0 && substr_count($ip, ".") == 0) {
        $js = 'var is6 = true';
} else {
        $js = 'var is6 = false';
}
print "<script>$js</script>";

And then to give the user a sense of excitement, animate showing them if they are v6 or v4. You’ll need jQuery for this, of course:

<div id="ipwhich" style="font-size:2em">?</div>
<script>
var showMe = 'v4!';
if(is6){
        var showMe = 'v6!';     
}
$("#ipwhich").delay(1000).hide().delay(1000).html(showMe).fadeIn();
</script>
</div>

I did up a live demo: give it a try!