Skip to content

Instantly share code, notes, and snippets.

@yookoala
Created May 31, 2023 10:26
Show Gist options
  • Save yookoala/581a010e64fc70e9cfbe53e721f18ab7 to your computer and use it in GitHub Desktop.
Save yookoala/581a010e64fc70e9cfbe53e721f18ab7 to your computer and use it in GitHub Desktop.
A simple PHP API endpoint to process both JSON and POST formdata
<?php
$method = $_SERVER['REQUEST_METHOD'] ?? null;
if ($method === 'POST') {
$content_type = preg_match('/^(.+?); (.+?)$/', $_SERVER['HTTP_CONTENT_TYPE'] ?? '', $matches)
? $matches[1]
: ($_SERVER['HTTP_CONTENT_TYPE'] ?? null);
// Parse input data by content type
$input = file_get_contents('php://input');
$data = match (strtolower($content_type)) {
'application/json' => json_decode($input),
default => $_POST,
};
header('Content-Type: application/json');
echo json_encode([
'method' => $method,
'content_type' => $content_type,
'raw' => $input,
'data' => $data,
]);
exit();
}
?>
<html>
<head>
<style>
.result {
border: 1px solid #ccc;
padding: 1em;
margin: 1em;
white-space: pre;
}
</style>
</head>
<body>
<div class="result" data-content-type="application/json; charset=utf-8"></div>
<div class="result" data-content-type="application/x-www-form-urlencoded; charset=utf-8"></div>
<script>
document.querySelectorAll('.result').forEach((element) => {
const contentType = element.getAttribute('data-content-type');
const body = (contentType.toLowerCase().startsWith('application/json'))
? JSON.stringify({ "tid": "123456", "amount": "9.99" })
: new URLSearchParams({ "tid": "123456", "amount": "9.99" });
fetch(<?=json_encode($_SERVER['REQUEST_URI'], JSON_UNESCAPED_SLASHES)?>, {
method: 'POST',
headers: {
'Content-Type': contentType,
},
body,
}).then((response) => {
return response.json();
}).then((data) => {
element.innerText = JSON.stringify(data, null, 2);
}).catch((error) => {
element.innerText = error;
});
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment