PHP获取PUT请求正文 [英] PHP get PUT request body

查看:733
本文介绍了PHP获取PUT请求正文的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在用PHP开发Restful Json-API.我想向items/:id发送一个PUT请求以更新一条记录.数据将作为application/json传输.

I'm currently developing a Restful Json-API in PHP. I want to send a PUT-Request to items/:id to update a record. The data will be transferred as application/json.

我想通过以下方式调用API

I want to call the API with

curl -H "Content-Type: application/json" -X PUT -d '{"example" : "data"}' "http://localhost/items/someid"

在服务器端,我无法检索请求正文.我尝试过

On the server side, I'm not able the retrieve the request body. I tried

file_get_contents("php://input");

但是这将返回一个空字符串. fopen()/fread()组合也不起作用.

but this returns an empty string. Also a fopen()/fread() combination doesn't work.

通过POST调用时,一切正常,我可以在服务器端完美地读取json.但是API不再是Restful.有人对此有解决方案吗?还有发送和接收Json的另一种方法吗?

When calling via POST, everything works great, I can read the json perfectly on the server side. But the API isn't Restful anymore. Does anyone have a solution for this? Is there another way to send and receive Json?

顺便说一句,我正在使用 Slim Framework 开发API.

btw, I'm developing the API with the Slim Framework.

推荐答案

php://input对于PUT请求仅可读一次:

php://input is only readable once for PUT requests:

注意:用php://input打开的流只能读取一次;该流不支持搜索操作.但是,根据SAPI的实现,有可能打开另一个php://input流并重新开始读取.仅在请求正文数据已保存的情况下才有可能.通常,POST请求就是这种情况,而其他请求方法(例如PUT或PROPFIND)则不是这种情况.

Note: A stream opened with php://input can only be read once; the stream does not support seek operations. However, depending on the SAPI implementation, it may be possible to open another php://input stream and restart reading. This is only possible if the request body data has been saved. Typically, this is the case for POST requests, but not other request methods, such as PUT or PROPFIND.

http://php.net/manual/en/wrappers.php.php

Slim框架已根据请求读取数据.从已被读取的Request对象中获取数据.

The Slim framework already reads the data upon request. Take the data from the Request object, into which it has been read.

这篇关于PHP获取PUT请求正文的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆