Last active
December 2, 2018 11:09
-
-
Save andybroomfield/8e10a61bc1e78e3cb1658397643baa49 to your computer and use it in GitHub Desktop.
Metaweather.com API proxy to implement cache and CORS headers
This file contains 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 | |
define ('API_URI_BASE', 'https://www.metaweather.com/api/'); | |
define ('CACHE_DIR', 'metaweather-cache'); | |
define ('CACHE_TIME', 3600); | |
// Create Cache Directory | |
$cache_name = sha1($_SERVER['REQUEST_URI']); | |
if (!is_dir(CACHE_DIR)) { | |
if (file_exists(CACHE_DIR)) { | |
die ('Cache dir is a file'); | |
} | |
mkdir(CACHE_DIR); | |
} | |
if (file_exists(CACHE_DIR.'/'.$cache_name) && filemtime(CACHE_DIR.'/'.$cache_name) >= (time() - CACHE_TIME)) { | |
// If cached, return the cached file | |
$json = file_get_contents(CACHE_DIR.'/'.$cache_name); | |
} else { | |
// Else make api request and cache | |
$method = (isset($_GET['method']) ? $_GET['method'] : null); | |
$apiCall = API_URI_BASE.$method.'/'; | |
switch ($method) { | |
case null: | |
$json = null; | |
break; | |
case 'location/search': | |
$query = (isset($_GET['query']) ? urlencode($_GET['query']) : null); | |
$lattlong = (isset($_GET['lattlong']) ? urlencode($_GET['lattlong']) : null); | |
if (!empty($query)) { | |
$json = file_get_contents($apiCall.'?query='.$query); | |
} elseif (!empty($lattlong)) { | |
$json = file_get_contents($apiCall.'?lattlong='.$lattlong); | |
} else { | |
$json = json_encode([]); | |
} | |
break; | |
default: | |
$json = file_get_contents($apiCall); | |
break; | |
} | |
// Write json to cach | |
file_put_contents(CACHE_DIR.'/'.$cache_name, $json); | |
} | |
// Output with CORS Header | |
header('Content-Type: application/json'); | |
header("Access-Control-Allow-Origin: *"); | |
echo $json; | |
exit; | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment