Created
December 25, 2018 20:23
-
-
Save markusand/c180a526f37a243f63b957e9bb475667 to your computer and use it in GitHub Desktop.
Simple cache proxy to throttle queries to APIs, for example to darksky.net
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/* Cache proxy for darksky.net API requests */ | |
define('API_KEY', '***********************'); | |
define('TIMEOUT', 10 * 60); // In seconds (10 minutes) | |
// Coordinates MUST be the first element in URL as https://api.server.io/v1/weather/[LAT,LON] | |
$params = explode('/', trim($_SERVER['PATH_INFO'], '/')); | |
$coords = filter_var(array_shift($params), FILTER_SANITIZE_STRING); | |
// Validate coordinates | |
if (empty($coords)) sendResponse(400, ["code" => 400, "message" => "Coordinates are required"]); | |
$latlon = explode(',', $coords); | |
if (count($latlon) != 2) sendResponse(400, ["code" => 400, "message" => "Invalid coordinates"]); | |
// Retrieve information | |
$url = 'https://api.darksky.net/forecast/'.API_KEY.'/'.$coords.'?exclude=[minutely,hourly]&units=si&lang=ca'; | |
$file = 'cache/'.md5($url).'.json'; | |
if (!file_exists($file) || (time() - filemtime($file) > TIMEOUT)) { | |
// Return from API & update cache | |
$response = file_get_contents($url); | |
if (!file_exists('cache')) mkdir('cache', 0777); | |
file_put_contents($file, $response); | |
sendResponse(200, $response); | |
} else sendResponse(200, file_get_contents($file)); // Return from cache | |
// Send HTTP response | |
function sendResponse($code, $response) { | |
header("HTTP/1.0 ".$code); | |
header('Content-type: application/json'); | |
echo is_array($response) | |
? json_encode($response, JSON_UNESCAPED_SLASHES | JSON_NUMERIC_CHECK) | |
: $response; | |
exit(); | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment