Skip to content

Instantly share code, notes, and snippets.

@sonictruth
Last active November 25, 2022 14:03
Show Gist options
  • Save sonictruth/af7866968f2469d22b42121c44b90678 to your computer and use it in GitHub Desktop.
Save sonictruth/af7866968f2469d22b42121c44b90678 to your computer and use it in GitHub Desktop.
Open Weather PHP caching proxy
<?
$origin = @$_SERVER['HTTP_ORIGIN'];
$lat = round(floatval($_GET['lat']),2);
$lon = round(floatval($_GET['lon']),2);
if($lat > 90 || $lat < -90 || $lon > 180 || $lon < -180 ) {
die('Invalid coordinates' . $lat . 'x' . $lon);
}
$cacheFile = 'cache_' . $lat . '_' . $lon;
if(
strpos($origin, "https://localhost") === 0 ||
strpos($origin, "https://sonictruth") === 0 ||
strpos($origin, "https://192.") === 0 ||
strpos($origin, "https://10.") === 0
) {
header("Access-Control-Allow-Methods: GET");
header("Access-Control-Allow-Origin: " . $origin . "");
}
function request() {
global $cacheFile, $lat, $lon;
$_GET['appid'] = 'xxxxxx';
$_GET['lat'] = $lat;
$_GET['lon'] = $lon;
$url =
"https://api.openweathermap.org/data/2.5/onecall?" . http_build_query($_GET) ;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
http_response_code($httpcode);
if ($httpcode === 200) {
file_put_contents($cacheFile , $output);
}
return $output;
}
clearstatcache();
$stat = @stat($cacheFile );
if($stat == false || ($stat && time() - $stat["mtime"] > 3000)) {
echo request();
} else {
echo file_get_contents($cacheFile );
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment