Igo*_*gor 17 php rest json curl restful-architecture
我正在构建一个PHP RESTful API,遵循本教程.以下函数应该在使用'put'方法时返回随请求一起发送的数据,每次都返回null:
file_get_contents('php://input')
.
我甚至已经下载并测试了教程中的完整代码示例,它仍然返回null.
我正在使用cURL和以下命令来测试'put'方法:
curl -i -X PUT -d '{"address":"Sunset Boulevard"}' http://localhost/clients/ryan
.
我已经浪费了很多时间,仍然没有阅读json数据.我究竟做错了什么?
确保没有重定向。
file_get_contents(php://input)
不通过重定向传递正文内容。
检查重定向的一种快速方法是使用 curl 检查 url。在命令行上:
curl -IL http://example.com/api
首先,我能够运行此代码,它工作正常:
--Terminal---------
//I ran this curl request against my own php file:
curl -i -X PUT -d '{"address":"Sunset Boulevard"}' http://localhost/test.php
--PHP--------------
//get the data
$json = file_get_contents("php://input");
//convert the string of data to an array
$data = json_decode($json, true);
//output the array in the response of the curl request
print_r($data);
Run Code Online (Sandbox Code Playgroud)
如果这不起作用,请检查控制台是否有错误和您的php设置:
tail -f /path/to/the/php/log/file
这样你就可以实际看到这些php调用的输出.file_get_contents(file://input): failed to open stream: no suitable wrapper could be found
这可能表示"file:// input"字符串的拼写错误或allow_url_fopen
在php中禁用的事实(如果不确定,请参阅#5)请记住,file_get_contents
只有allow_url_fopen
在PHP设置中设置为true 时才有效.这是在php.ini中设置的东西,但您也可以在运行时通过在其他代码之前写下以下代码的内容来更改设置:
ini_set("allow_url_fopen", true);
Run Code Online (Sandbox Code Playgroud)我用以下代码编写了一个头文件:
if($_SERVER["REQUEST_METHOD"] == "POST" && $_SERVER["CONTENT_TYPE"] == "application/json")
{
$data = file_get_contents("php://input", false, stream_context_get_default(), 0, $_SERVER["CONTENT_LENGTH"]);
global $_POST_JSON;
$_POST_JSON = json_decode($_REQUEST["JSON_RAW"],true);
// merge JSON-Content to $_REQUEST
if(is_array($_POST_JSON)) $_REQUEST = $_POST_JSON+$_REQUEST;
}
Run Code Online (Sandbox Code Playgroud)
它检查正确的内容类型,并且只读取与 Content-Length 标头中指定的一样多的帖子输入。当收到有效的 JSON 时,它会创建一个全局数组 $_POST_JSON。
因此,您可以像使用 url 编码的 POST 值一样使用 JSON 内容。
例子:
echo $_POST_JSON["address"];
// or
echo $_REQUEST["address"];
Run Code Online (Sandbox Code Playgroud)
对我来说,这个问题突然开始。
我已经安装了ssl证书。
当我检查响应代码时,它显示了 301,然后我意识到并将
http://更改
为
http s ://
并使用 file_get_contents('php://input') 返回所有请求。
在您的示例中,curl 调用:
将 s 放在 http 之后,如下所示:
curl -i -X PUT -d '{"address":"Sunset Boulevard"}' https://localhost/clients/ryan
正确的函数调用是:
file_get_contents("php://input");
Run Code Online (Sandbox Code Playgroud)
您应该收到一条错误消息,指出该信息php:input
不存在...
在任何情况下,PUT
它都用于将文件上传到服务器,假设服务器支持它。通常您会使用适合内容的标题POST
。Content-Type
归档时间: |
|
查看次数: |
49977 次 |
最近记录: |