php - Resful API json_decode(file_get_contents("php://input")); 总是返回 null
问题描述
我是新手,正在尝试使用 PHP 构建 Restful 服务。到目前为止,我有两种方法可用,一种是列出用户,另一种是在数据库中创建条目。第一个工作正常,我调用 API 并获取我想要的列表。对于第二个, json_decode(file_get_contents("php://input")); 始终为空。
这是我调用远程 API 的方法
public static function remoteApiCall($data=0, $method='GET', $apiURI=API_LIST_AQT_URI, $remoteServer=PUBLIC_LOCATION) {
try {
$curl = curl_init();
$url = $remoteServer.$apiURI;
switch ($method)
{
case "POST":
curl_setopt($curl, CURLOPT_POST, true);
if ($data)
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
break;
case "PUT":
curl_setopt($curl, CURLOPT_PUT, true);
break;
default:
if ($data)
$url = sprintf("%s?%s", $url, http_build_query($data));
}
// Optional Authentication:
#curl_setopt($curl, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
#curl_setopt($curl, CURLOPT_USERPWD, "username:password");
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($curl);
curl_close($curl);
return json_decode($result, true);
} catch(PDOException $e) {
echo $e->getMessage();
return false;
}
这是远程服务器上的 create.php
<?php
session_start();
header("Access-Control-Allow-Origin: *");
header("Content-Type: application/json; charset=UTF-8");
header("Access-Control-Allow-Methods: POST");
header("Access-Control-Max-Age: 3600");
header("Access-Control-Allow-Headers: Content-Type, Access-Control-Allow-Headers, Authorization, X-Requested-With");
// instantiate object
include '../objects/remoteObject.php';
$_SESSION["ROOT"] = true;
$ano = new RemoteObject();
// get posted data
$data = json_decode(file_get_contents("php://input"));
var_dump($data);
(...)
这是我在代码中调用我的方法的方式
$data = array("ref" => $ref, "idUser" => $idUser;
var_dump($data);
$resulAnoCreation = MyAPI::remoteApiCall($data, "POST", API_CREATE_URI, PUBLIC_LOCATION);
我跟着这个教程 我错过了什么吗?
提前致谢
忘了提到我的呼叫和远程应用程序都在我的本地主机上,在 Windows 环境中运行。
另一个更新:我正在使用 Postman Chrome 扩展调试我的创建方法,正如您在下面的捕获中看到的那样。即使你 $_POST 有正确的内容,file_get_contents("php://input") 和 $HTTP_RAW_POST_DATA 都是空的。正如我所说,我在 Windows 环境中。我是否需要启用任何特殊的环境变量才能访问 php://input ?
解决方案
经过一番挣扎,问题似乎出在windows环境上。所以我在 windows 中测试时使用了 $_POST,在 unix 生产环境中使用了 file_get_contents("php://input")。
推荐阅读
- oracle - 在哪里下载 shp2sdo 实用程序来处理 shape 文件以隐藏到 oracle 空间
- function - 按条件反应本机导航
- java - okhttp3 的空响应
- r - 管道 R 中字符的拆分向量 - 仅保留拆分的第一部分
- python - 函数评估发散,取决于输入精度
- javascript - 在平面列表中添加删除按钮反应原生
- python - Python让类函数打印它调用的函数的文档字符串
- python - conda环境被激活,但是python控制台说环境没有被激活
- reactjs - 显示文本而不是控制台日志
- vb.net - 使用 sudo 执行 SSH 命令行,然后输入密码