我有以下 PHP 文件:
<?php
// ***************************************************
if (!function_exists('gzdecode'))
{
function gzdecode($data)
{
// strip header and footer and inflate
return gzinflate(substr($data, 10, -8));
}
}
// ***************************************************
// get compressed (gzip) POST request into a string
$comprReq = file_get_contents('php://input');
// get decompressed POST request
$decomprReq = gzdecode($comprReq);
// decode to json
$jsonData = json_decode($decomprReq, true);
// create file if not exits or open file if exists
$file = fopen('omni.json', 'a');
if ($jsonData === null)
{
// mark as invalid and save. send HTTP response
fwrite($file, 'invalid json');
fclose($file);
header('HTTP/1.0 400 Bad Request');
}
else
{
// write json and save. send HTTP response
fwrite($file, $jsonData);
fclose($file);
header('HTTP/1.0 200 OK');
}
?>
这个想法是它接受一个 JSON HTTP POST(压缩 - gzipped),解压缩它,并在新的(如果不存在)或现有的 json 文件的末尾附加 json(JSON 格式)。它还应根据结果发回 200 OK 或 400 BAD REQUEST HTTP 响应代码。
我尝试用 Postman 来测试它通过发送以下内容:
是的,没有任何反应。服务器上未创建任何 JSON 文件。响应始终为 200 OK。
知道我做错了什么吗?
最佳答案
检查您的文件路径和权限(使用 __DIR__
指定文件名的完整路径)。变量 $decomprReq 为 false,因为您以明文形式发送内容而不是 gzip 压缩。 $comprReq 具有您发送的 json 值。我测试了您的代码,看起来没问题。
关于PHP 不解析 HTTP POST(压缩)JSON 请求?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40333852/