Skip to content

Instantly share code, notes, and snippets.

@pajcho
Last active May 25, 2018 11:59
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pajcho/4cc9ea54cf20085b2f45 to your computer and use it in GitHub Desktop.
Save pajcho/4cc9ea54cf20085b2f45 to your computer and use it in GitHub Desktop.
Get weather information based on IP
<?php
function get_client_ip()
{
$ipaddress = '';
if (getenv('HTTP_CLIENT_IP'))
$ipaddress = getenv('HTTP_CLIENT_IP');
else if (getenv('HTTP_X_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_X_FORWARDED_FOR');
else if (getenv('HTTP_X_FORWARDED'))
$ipaddress = getenv('HTTP_X_FORWARDED');
else if (getenv('HTTP_FORWARDED_FOR'))
$ipaddress = getenv('HTTP_FORWARDED_FOR');
else if (getenv('HTTP_FORWARDED'))
$ipaddress = getenv('HTTP_FORWARDED');
else if (getenv('REMOTE_ADDR'))
$ipaddress = getenv('REMOTE_ADDR');
else
$ipaddress = 'UNKNOWN';
return $ipaddress;
}
$ip = get_client_ip(); // the IP address to query
//test ip
//$ip = "95.180.67.153"; // Beograd, Rakovica
$query = @unserialize(file_get_contents('http://ip-api.com/php/' . $ip));
if ($query && $query['status'] == 'success')
{
//get Coords
$lat = $query['lat'];
$lon = $query['lon'];
$url = "http://api.openweathermap.org/data/2.5/weather?lat={$lat}&lon={$lon}";
$djson = file_get_contents($url);
var_dump(json_decode($djson));
}
else
{
$url = "http://api.openweathermap.org/data/2.5/weather?q=Paris";
$djson = file_get_contents($url);
var_dump(json_decode($djson));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment