-
Notifications
You must be signed in to change notification settings - Fork 20
/
Copy pathapi.php
57 lines (53 loc) · 1.37 KB
/
api.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
<?php
// Get the request method
$method = getMethod();
// Set the header to application/json
header('Content-Type: application/json');
try {
// Switch the base URL
switch(getBaseUrl()){
case "/traffic": {
// include script to get data
include 'getTrafficData.php';
// Render JSON response with the result data
renderJsonResponse($result);
break;
}
default: {
// No function found for the given base URL
throw new \Exception("API function not found.", 404);
}
}
} catch (Exception $ex) {
// Render JSON error response with the exception data
renderJsonResponse(array("error" => array("message"=>$ex->getMessage(), "code" => $ex->getCode())));
}
exit(0);
/**
* Get the request method
* Return GET, POST, DELETE or PUT
*
* @return string
*/
function getMethod() {
return strtoupper($_SERVER['REQUEST_METHOD']);
}
/**
* Get the base URL without the script name and jquery params
*
* @return string
*/
function getBaseUrl(){
$url = str_replace($_SERVER['SCRIPT_NAME'], "", $_SERVER['REQUEST_URI']);
return explode("?", $url)[0];
}
/**
* Get a JSON string from the $data array
*
* @param array $data
* @return string
*/
function renderJsonResponse(array $data = array()) {
$data['request_time'] = time();
echo json_encode($data);
}