Use response_add("key", "value");
to add a key and a value to the JSON response.
Last active
September 16, 2018 09:54
-
-
Save MarvinJWendt/c5028881a24edd88103666bd18ca6f63 to your computer and use it in GitHub Desktop.
PHP REST API template with JSON response (single file | Usage: see x-README.md)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
//Uncomment to show errors | |
//ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL); | |
$response = array(); | |
$method = $_SERVER['REQUEST_METHOD']; | |
header('Content-Type: application/json'); | |
switch ($method) { | |
case 'GET': | |
invalid_method(); | |
break; | |
case 'POST': | |
invalid_method(); | |
break; | |
case 'PUT': | |
invalid_method(); | |
break; | |
case 'PATCH': | |
invalid_method(); | |
break; | |
case 'DELETE': | |
invalid_method(); | |
break; | |
case 'COPY': | |
invalid_method(); | |
break; | |
case 'HEAD': | |
invalid_method(); | |
break; | |
case 'OPTIONS': | |
invalid_method(); | |
break; | |
case 'LINK': | |
invalid_method(); | |
break; | |
case 'UNLINK': | |
invalid_method(); | |
break; | |
case 'PURGE': | |
invalid_method(); | |
break; | |
case 'LOCK': | |
invalid_method(); | |
break; | |
case 'UNLOCK': | |
invalid_method(); | |
break; | |
case 'PROPFIND': | |
invalid_method(); | |
break; | |
case 'VIEW': | |
invalid_method(); | |
break; | |
default: | |
invalid_method(); | |
break; | |
} | |
echo(json_encode($response)); //Send response as JSON | |
function response_add($key, $value) { | |
global $response; | |
array_push($response, array($key => $value)); | |
} | |
function invalid_method() { | |
global $method; | |
response_add("error", "Invalid method! (" . $method . ")"); | |
http_response_code(405); //Send status code 405 (Method Not Allowed) | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment