WP-Mix

A fresh mix of code snippets and tutorials

PHP Geo IP Lookup

Here is a nice PHP snippet for GeoIP lookups. As written the script uses api.hostip.info for the lookup service, but that is easily changed as needed (GeoIP lookup services change or go offline constantly). So for what it’s worth, figured it was worth sharing rather than complete and utter deletion. Yes I am a code hoarder LOL.

So this script is pretty raw, but it does show how to perform some essential IP-lookup functionality, like using PHP cURL if available, otherwise fallback to fsockopen() technique. Consider it as a starting point for further development and experimentation.

$ip = '123.456.789.000';

$flag_url  = "http://api.hostip.info/flag.php?ip=". $ip;
$new_url   = shapeSpace_follow_redirect($flag_url);
$flag_data = file_get_contents($new_url);
$flag      = base64_encode($flag_data);

echo $flag;


function shapeSpace_follow_redirect($url) {
	$redirect_url = null;
	if (function_exists("curl_init")) {
		$ch = curl_init($url);
		curl_setopt($ch, CURLOPT_HEADER, true);
		curl_setopt($ch, CURLOPT_NOBODY, true);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		$response = curl_exec($ch);
		curl_close($ch);
	} else {
		$url_parts = parse_url($url);
		$sock = fsockopen($url_parts['host'], (isset($url_parts['port']) ? (int)$url_parts['port'] : 80));
		$requesturl = "HEAD " . $url_parts['path'] . (isset($url_parts['query']) ? '?'.$url_parts['query'] : '') . " HTTP/1.1\r\n";
		$requesturl .= 'Host: ' . $url_parts['host'] . "\r\n";
		$requesturl .= "Connection: Close\r\n\r\n";
		fwrite($sock, $requesturl);
		$response = fread($sock, 2048);
		fclose($sock);
	}
	$header = "Location: ";
	$pos = strpos($response, $header);
	if ($pos === false) {
		return false;
	} else {
		$pos += strlen($header);
		$redirect_url = substr($response, $pos, strpos($response, "\r\n", $pos)-$pos);
		return $redirect_url;
	}
}

Notes: As written this script uses the shapeSpace_follow_redirect() function to lookup the country flag associated with the given IP address. The basic technique can be extended or modified to return just about any IP/Geo information that is needed. You may need to experiment with different GeoIP-lookup APIs in order to get the desired information (e.g., city, state, country, zip code, et al).

Also note this is provided for experimentation only, not intended for use on live production sites without proper testing, etc.

★ Pro Tip:

USP Pro