Merge branch 'dummy-session'
[todo-rest-api_edi2-2023.git] / rest-api.php
blob1f948bf0b8b803e4af932e9d3d6c25391b2e5722
1 <?php
3 // @see https://www.php.net/manual/en/session.configuration.php
4 ini_set("session.use_cookies", 0);
5 ini_set("session.use_only_cookies", 0);
6 ini_set("session.use_trans_sid", 0);
7 ini_set("session.cache_limiter", "");
8 session_id('dummy-session-id');
9 session_start();
11 // Response 'Content-Type' header
12 header('Content-Type: application/json');
14 // Flag that tells if the 'Accept' header in the request is invalid
15 $invalidAccept = '*/*' != $_SERVER['HTTP_ACCEPT'] && 'application/json' != $_SERVER['HTTP_ACCEPT'];
17 // Do not accept requests which 'Accept' header isn't one of the above
18 if ($invalidAccept) {
19 header('HTTP/1.1 406 Not Acceptable');
20 exit;
23 // Get request method and path
24 $method = strtolower($_SERVER['REQUEST_METHOD']);
25 $uri = parse_url($_SERVER['REQUEST_URI']);
26 $path = trim(trim($uri['path']), '/');
28 // Default 'resource' and 'id' values
29 $resource = 'root';
30 $id = null;
32 // Get 'resource' and 'id' values
33 if ($path) {
34 $path = explode('/', $path);
35 $resource = $path[0];
36 if (!empty($path[1])) {
37 $id = (int) $path[1];
41 // Default 'input' value
42 $input = null;
44 // Get 'input' value
45 if ('post' == $method || 'put' == $method) {
46 $input = file_get_contents('php://input');
49 // File name (convention) from where the logic will be loaded
50 $fileName = strtolower("{$method}_{$resource}");
51 $fileName.= $id ? '_id' : '';
52 $fileName.= '.php';
54 // Function name (convention) that handles the request
56 // The function will receive the following parameters:
58 // * Parameter 1: int|null $id The item ID (if it's present)
59 // * Parameter 2: string|null $input The input value (if it's present)
60 $functionName = 'handle_request';
62 // Load and call the logic that handles the request
63 if (is_readable($fileName)) {
64 require_once($fileName);
65 if (function_exists($functionName)) {
66 $functionName($id, $input);
67 exit;
71 // Default (404) response code
72 header('HTTP/1.1 404 Not Found');