Make `preflight` request pass okay
[asis23-votoe-server.git] / rest-api.php
blobc67123858833b82c8e0bf712f4142d3a96f32ede
1 <?php
3 // Response 'Content-Type' header
4 header('Content-Type: application/json');
6 // @see https://stackoverflow.com/a/61856861
7 header("Access-Control-Allow-Origin: *");
8 header('Access-Control-Allow-Methods: GET, POST, PATCH, PUT, DELETE, OPTIONS');
9 header("Access-Control-Allow-Headers: Content-Type, Accept, Origin, Access-Control-Allow-Headers");
11 if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
12 return;
15 // Flag that tells if the 'Accept' header in the request is invalid
16 $invalidAccept = '*/*' != $_SERVER['HTTP_ACCEPT'] && 'application/json' != $_SERVER['HTTP_ACCEPT'];
18 // Do not accept requests which 'Accept' header isn't one of the above
19 if ($invalidAccept) {
20 header('HTTP/1.1 406 Not Acceptable');
21 exit;
24 // Get request method and path
25 $method = strtolower($_SERVER['REQUEST_METHOD']);
26 $uri = parse_url($_SERVER['REQUEST_URI']);
27 $path = trim(trim($uri['path']), '/');
29 // Default 'resource' and 'id' values
30 $resource = 'root';
31 $id = null;
33 // Get 'resource' and 'id' values
34 if ($path) {
35 $path = explode('/', $path);
36 $resource = $path[0];
37 if (!empty($path[1])) {
38 $id = (int) $path[1];
42 // Default 'input' value
43 $input = null;
45 // Get 'input' value
46 if ('post' == $method || 'put' == $method) {
47 $input = file_get_contents('php://input');
50 // File name (convention) from where the logic will be loaded
51 $fileName = strtolower("{$method}_{$resource}");
52 $fileName.= $id ? '_id' : '';
53 $fileName.= '.php';
55 // Function name (convention) that handles the request
57 // The function will receive the following parameters:
59 // * Parameter 1: int|null $id The item ID (if it's present)
60 // * Parameter 2: string|null $input The input value (if it's present)
61 $functionName = 'handle_request';
63 // Load and call the logic that handles the request
64 if (is_readable($fileName)) {
65 require_once($fileName);
66 if (function_exists($functionName)) {
67 $functionName($id, $input);
68 exit;
72 // Default (404) response code
73 header('HTTP/1.1 404 Not Found');