Jump to content

[Solved] There are some API for the geolocation? 


Marco Ro
 Share

Recommended Posts

There are some API for the geolocation? 

 

To explain the situation better:

I have to hidden some element for not Italian country.

At moment I have do this:

$.get("http://ipinfo.io", function (response) {
     var country = response.country;
     if(country != "IT"){
       $('.my-class').hide();
     }
}, "jsonp");

But I know it's not a good way!! 

 

I try to insert this is a php if condition to not print nothing, but is not easy let js and php work together. 

$.get("http://ipinfo.io", function (response) {
    $("#country").val(response.country); 
}, "jsonp");

<input hidden id="country" type="text" name="country" value="">

This work well and show me the country code (eg. IT). I try to get this value and insert in a IF but of course the $_GET can't work...

$country = $_GET['country']; 
$nation = "IT"; 
<?php if ($country != $nation): ?> 
	Code to hidden here... 
<?php endif; ?>

 

Does PW have any APIs that I can use? or do you have any idea.
I know I'm not a php-hero 😥

Link to comment
Share on other sites

thank you @bernhard  Now work well 😍

This is the code if some one need

<?PHP

function getUserIP()
{
    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];

    if(filter_var($client, FILTER_VALIDATE_IP))
    {
        $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
        $ip = $forward;
    }
    else
    {
        $ip = $remote;
    }

    return $ip;
}


$user_ip = getUserIP();

echo "ip: " . $user_ip . "<br />";

$http = new WireHttp();
$url = "http://ipinfo.io/{$user_ip}/country";
$response = $http->get($url, ['country' => '']);
$country = filter_var ( $response, FILTER_SANITIZE_ENCODED); // the country have a hiddend code

echo = $country; // This is the correct code to use 
?>

 

In both case that return the correct Country Code. :) 

  • Like 1
Link to comment
Share on other sites

glad it worked. 2 things:

TracyDebugger helps a lot when trying new code. You can use the console to execute code quickly and use d() to dump instead of echo. This makes things a lot more readable, especially when you are dealing with arrays and objects:

ipinfo.png.a0a391cfb2f0ed17dcdff7eead42b3c0.png

As you can see, getJSON might also be nice to use here ;)

  • Like 1
  • Thanks 1
Link to comment
Share on other sites

  • 4 years later...

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...