3 // Response 'Content-Type' header
4 header('Content-Type: application/json');
6 // Flag that tells if the 'Accept' header in the request is invalid
7 $invalidAccept = '*/*' != $_SERVER['HTTP_ACCEPT'] && 'application/json' != $_SERVER['HTTP_ACCEPT'];
9 // Do not accept requests which 'Accept' header isn't one of the above
11 header('HTTP/1.1 406 Not Acceptable');
15 // Get request method and path
16 $method = strtolower($_SERVER['REQUEST_METHOD']);
17 $uri = parse_url($_SERVER['REQUEST_URI']);
18 $path = trim(trim($uri['path']), '/');
20 // Default 'resource' and 'id' values
24 // Get 'resource' and 'id' values
26 $path = explode('/', $path);
28 if (!empty($path[1])) {
33 // Default 'input' value
37 if ('post' == $method ||
'put' == $method) {
38 $input = file_get_contents('php://input');
41 // File name (convention) from where the logic will be loaded
42 $fileName = strtolower("{$method}_{$resource}");
43 $fileName.= $id ?
'_id' : '';
46 // Function name (convention) that handles the request
48 // The function will receive the following parameters:
50 // * Parameter 1: int|null $id The item ID (if it's present)
51 // * Parameter 2: string|null $input The input value (if it's present)
52 $functionName = 'handle_request';
54 // Load and call the logic that handles the request
55 if (is_readable($fileName)) {
56 require_once($fileName);
57 if (function_exists($functionName)) {
58 $functionName($id, $input);
63 // Default (404) response code
64 header('HTTP/1.1 404 Not Found');