我有一个脚本,试图使用HTTP PUT向我的网站发送数据。通常情况下,我只需使用file_get_contents('php://input')
从输入流中读取即可。然而,当我在Laravel中尝试这样做时,我什么也没得到!为什么?我该如何读取原始输入数据?
Laravel会拦截所有的输入。如果你使用的是 PHP 5.6 之前的版本,php://input
流只能读取一次。这意味着你需要从框架中获取数据。你可以通过访问 Request
实例上的 getContent
方法来实现,就像这样:
$content = Request::getContent(); // Using Request facade
/* or */
$content = $request->getContent(); // If you already have a Request instance
// lying around, from say the controller
由于Illuminate\Request
继承了Symfony\Component\HttpFoundation\Request
,并且getContent
在这里定义:http://api.symfony.com/3.0/Symfony/Component/HttpFoundation/Request.html#method_getContent
Request::json($key, $default);
来返回JSON有效负载中特定键的值。当您使用Request::getContent();
时,您可能会遇到错误,因为最新的Symfony Request模块(作为Laravel的Request模块的基础)不再提供getContent
作为静态方法。相反,我使用Request::createFromGlobals()->getContent();
。
参考:访问请求数据
Request::getContent();
- alexrussell$content = request()->getContent();
也可以工作。 - refik