-
Notifications
You must be signed in to change notification settings - Fork 1
/
openweathermap.php
71 lines (53 loc) · 1.71 KB
/
openweathermap.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
<?php
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 2020 05:00:00 GMT');
header('Content-type: application/json');
$return["status"] = "error";
$return["code"] = "404";
$return["string"] = "No action was taken";
$city = "7290253"; // Berlin Tempelhof
$appid = "29da08fd88015c5b317d9aa3df52fa38";
$url = "http://api.openweathermap.org/data/2.5/weather?id=".$city."&units=metric&appid=".$appid."";
$cacheFile = 'cache' . DIRECTORY_SEPARATOR . md5($url);
if (file_exists($cacheFile)) {
$fh = fopen($cacheFile, 'r');
$cacheTime = trim(fgets($fh));
// if data was cached recently, return cached data
if ($cacheTime > strtotime('-15 minutes')) {
$weather = fread($fh, filesize($cacheFile));
$return["status"] = "success";
$return["code"] = "1";
$return["string"] = "Weather data successfully retrieved from cache";
$return["data"] = json_decode($weather);
echo json_encode($return);
return;
}
// else delete cache file
fclose($fh);
unlink($cacheFile);
}
$dw = curl_init($url);
if($dw){
curl_setopt($dw, CURLOPT_RETURNTRANSFER, true);
$dataWeather = curl_exec($dw);
if (curl_error($dw)) {
$return["status"] = "error";
$return["code"] = "0";
$return["string"] = "Error retrieving live weather data";
curl_close($dw);
echo json_encode($return);
return;
}
curl_close($dw);
$weather = json_decode($dataWeather);
$return["status"] = "success";
$return["code"] = "1";
$return["string"] = "Live weather data successfully retrieved";
$return["data"] = $weather;
$fh = fopen($cacheFile, 'w');
fwrite($fh, time() . "\n");
fwrite($fh, $dataWeather);
fclose($fh);
}
echo json_encode($return);
?>