Posted By

jspicher on 07/23/11


Tagged


Versions (?)

geoip targeting


 / Published in: PHP
 

  1. <?
  2.  
  3. function geoip($ip = false, $api_key = 'cfea6a359ca8f852da3914055958db09bbcc63d4443b9ad21724dc3a9e8b4295'){
  4. if(!$ip) $ip = $_SERVER['REMOTE_ADDR'];
  5.  
  6. //you can get your own api key here: http://ipinfodb.com/register.php
  7. //this function attempts to call via curl, but will fall back to file_get_contents
  8. //if curl is not available.
  9. $url = "http://api.ipinfodb.com/v3/ip-city/?key={$api_key}&ip={$_SERVER['REMOTE_ADDR']}&format=json&callback=";
  10. if(function_exists('curl_init') && 1==0){
  11. $ch = curl_init();
  12. curl_setopt($ch, CURLOPT_VERBOSE, 1);
  13. curl_setopt($ch, CURLOPT_URL, $url);
  14. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  15. curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
  16. $r = json_decode(curl_exec($ch), 1);
  17. curl_close($ch);
  18. }else{
  19. $r = json_decode(file_get_contents($url), 1);
  20. }
  21.  
  22. if(in_array(strtolower($r['regionName']), array('idaho', 'colorado'))){
  23. return true;
  24. }
  25. return false;
  26. }
  27.  
  28.  
  29. // Example usage of the function below:
  30. if(geoip()):
  31. ?>
  32.  
  33. is from idaho, or colorado.
  34.  
  35. <? else: ?>
  36.  
  37. nope not form idaho, or colorado.
  38.  
  39. <? endif; ?>

Report this snippet  

You need to login to post a comment.