You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
rest-api/test.php

74 lines
2.1 KiB

<?php
/*
* New PHP REST Framework
*
* Using Following SPECS
* - HTTP Status Codes https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Status
* - HTTP Methods https://developer.mozilla.org/en-US/docs/Web/HTTP/Reference/Methods
* - REST API https://restfulapi.net/http-methods/
*/
/**
* Determines whether the incoming request has a JSON-based Content-Type.
*
* @param string|null $contentType Optional override for testing or CLI use.
* @return bool True if the Content-Type indicates JSON.
*/
function req_isjson(?string $contentType = null): bool {
// Get the header from the server if not provided
$type = $contentType ?? ($_SERVER['CONTENT_TYPE'] ?? '');
// Normalize and strip parameters like "; charset=utf-8"
$type = strtolower(trim(explode(';', $type)[0]));
// Known JSON-based media types
$jsonTypes = [
'application/json',
'application/ld+json',
'application/vnd.api+json', // JSON:API spec
'text/json', // Rare but occasionally seen
];
return in_array($type, $jsonTypes, true);
}
function req_method($supported = ['GET','PUT','POST','DELETE','HEAD','OPTIONS'],?string $method = null): string {
// Get the header from the server if not provided
$method = $method ?? ($_SERVER['REQUEST_METHOD'] ?? '');
if (!in_array($_SERVER['REQUEST_METHOD'], $supported)) {
http_response_code(405);
header('Allow: '. join(',',$supported));
exit;
}
return $method;
}
if (req_isjson()) {
$raw = file_get_contents('php://input');
$post =json_decode($raw,true,1000,JSON_INVALID_UTF8_IGNORE);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new JSONException('JSON: '.json_last_error_msg());
}
} else {
$post = $_REQUEST;
}
var_dump($_POST);
$req = (object)[
'isjson' => req_isjson(),
'method' => req_method(['GET','POST']),
'path' => $_SERVER['PATH_INFO'] ?? '/',
'post' => $post,
];
$res = (object)[
'result' => 'ok',
'req' => $req,
];
header('Content-Type: application/json');
echo json_encode([$res], JSON_UNESCAPED_SLASHES|JSON_PRETTY_PRINT);