Display ads depending on the country using PHP

From The IT Community
Jump to: navigation, search




If you are using ads on your site you might want to display them depending on the country the user is from. A easy way to do this is using a IP-database in combination with PHP.


Here is how to display ads depending on the country using PHP:

  • First, download the database, extract it and put it on your server.


  • Then, put this script in a .php file on your server to check the country code of your user and display ads accordingly:
<?
$IPaddress=$_SERVER['REMOTE_ADDR']; 
$two_letter_country_code=iptocountry($IPaddress);

 switch ($two_letter_country_code) {
	  case "AT":
	    print '
		
The code for Austria goes here!
		
';


	    break;
     case "DE":
	    print '

The code for Germany goes here!
 
';
	    break;
     
	  default:
	    print '
		
 The code for all other Countries goes here!		
		
		';
 }

function iptocountry($ip) {    
    $numbers = preg_split( "/\./", $ip);    
    include("ip_files/".$numbers[0].".php");
    $code=($numbers[0] * 16777216) + ($numbers[1] * 65536) + ($numbers[2] * 256) + ($numbers[3]);    
    foreach($ranges as $key => $value){
        if($key<=$code){
            if($ranges[$key][0]>=$code){$two_letter_country_code=$ranges[$key][1];break;}
            }
    }
    if ($two_letter_country_code==""){$two_letter_country_code="unkown";}
    return $two_letter_country_code;
}
?>


Replace the "The code goes here!" lines with your ads for that country. When you now use a web browser to access this page, the rights ads will be displayed, depending on the country you are in.



Was this article helpful? Then please donate to keep The IT Community alive...

If you found this article helpful please share it, comment and help others by writing your own article.






Translate this page: