PHP 7 Script to Display Website Visitor Country Flag Using ipinfodb API in Browser Full Project For Beginners

  • Post author:
  • Post category:PHP
  • Post comments:0 Comments

 

Welcome folks today in this blog post we will be displaying website visitor country flag using ipinfodb api in browser using php 7.All the full source code of the application is given below.

 

 

 

Get Started

 

 

 

In order to get started you need to make an index.php file and copy paste the following code

 

 

index.php

 

 

<?php
function visitor_country($ipinfodb_api)
{
    // Get the IP address of the visitor
    $ip_address = '';
    if (getenv('HTTP_CLIENT_IP'))
        $ip_address = getenv('HTTP_CLIENT_IP');
    else if(getenv('HTTP_X_FORWARDED_FOR'))
        $ip_address = getenv('HTTP_X_FORWARDED_FOR');
    else if(getenv('HTTP_X_FORWARDED'))
        $ip_address = getenv('HTTP_X_FORWARDED');
    else if(getenv('HTTP_FORWARDED_FOR'))
        $ip_address = getenv('HTTP_FORWARDED_FOR');
    else if(getenv('HTTP_FORWARDED'))
       $ip_address = getenv('HTTP_FORWARDED');
    else if(getenv('REMOTE_ADDR'))
        $ip_address = getenv('REMOTE_ADDR');
    else
        $ip_address = 'UNKNOWN';
   
// Retrive visitor's JSON data from IP address
$ipinfodb_json = file_get_contents("http://api.ipinfodb.com/v3/ip-city/?format=json&key=".$ipinfodb_api."&ip=".$ip_address."");
// Convert the JSON data into array
$ipinfodb_arr = json_decode($ipinfodb_json);
// Get the country from the array into lower case
$country_code = strtolower($ipinfodb_arr->countryCode);

return $country_code;
}
?>


<?php
    $country_code = visitor_country("IPInfoDB_API_KEY");
 ?>
<img width="110px" src="flags/svg/<?php echo $country_code; ?>.svg">

Leave a Reply