简体   繁体   English

file_get_contents('php://input') 总是返回一个空字符串

[英]file_get_contents('php://input') always returns an empty string

I'm building a PHP RESTful API, following this tutorial.我正在按照教程构建一个 PHP RESTful API。 The following function, which should return the data sent with the request when the 'put' method is used, returns null every time:下面的function,使用'put'方法时应该返回随请求发送的数据,每次返回null:

file_get_contents('php://input') . file_get_contents('php://input')

I've even downloaded and tested the full code example in the tutorial and it still returns null.我什至下载并测试了教程中的完整代码示例,它仍然返回 null。

I'm using cURL and the following command in order to test the 'put' method:我正在使用 cURL 和以下命令来测试“put”方法:

curl -i -X PUT -d '{"address":"Sunset Boulevard"}' http://localhost/clients/ryan . curl -i -X PUT -d '{"address":"Sunset Boulevard"}' http://localhost/clients/ryan

I've wasted days on this and still haven't gotten it to read the json data.我已经在这上面浪费了几天时间,但仍然没有得到它来读取 json 数据。 What am I doing wrong?我究竟做错了什么?

As noted elsewhere on the web , php://input content does not get through if request is redirected.正如网络上其他地方指出的,如果请求被重定向, php://input内容将无法通过。 Maybe your web server has a redirect from an URL starting with www to an URL without www, or from URLs using HTTP to URLs using HTTPS.也许您的 Web 服务器已从以 www 开头的 URL 重定向到不带 www 的 URL,或者从使用 HTTP 的 URL 重定向到使用 HTTPS 的 URL。 Check your web server logs to verify this, and act accordingly to avoid the redirection when making calls to the web service.检查您的 Web 服务器日志以验证这一点,并在调用 Web 服务时采取相应措施以避免重定向。

First off, i was able to run this code and it worked fine:首先,我能够运行此代码并且运行良好:

--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);

If that doesn't work, check the console for errors and your php settings:如果这不起作用,请检查控制台是否有错误和您的 php 设置:

  1. the curl url you used, make sure that url is actually working and not returning errors.您使用的 curl url,请确保 url 实际工作并且不返回错误。
  2. open up another terminal / console window and run tail -f /path/to/the/php/log/file so you can actually see the output of these php calls.打开另一个终端/控制台窗口并运行tail -f /path/to/the/php/log/file以便您可以实际看到这些 php 调用的输出。
  3. often people get this error: file_get_contents(file://input): failed to open stream: no suitable wrapper could be found which can indicate either a typo of the "file://input" string or the fact that allow_url_fopen is disabled in php (see #5 if unsure)通常人们会收到此错误: file_get_contents(file://input): failed to open stream: no suitable wrapper could be found这可能表明“file://input”字符串的拼写错误或allow_url_fopen在php(如果不确定,请参阅#5)
  4. make sure your code is correct, and by that I mean make sure you're not typing in incorrect arguments and things... stuff that doesn't necessarily get underlined in netbeans.确保你的代码是正确的,我的意思是确保你没有输入不正确的参数和东西......在netbeans中不一定要加下划线的东西。
  5. remember, file_get_contents only works when allow_url_fopen is set to true in your PHP settings.请记住, file_get_contents仅在 PHP 设置中将allow_url_fopen设置为 true 时才有效。 thats something that is set in php.ini, but you can also change settings at run time by writing something along the lines of the following code before the other code:这是在 php.ini 中设置的内容,但您也可以在运行时更改设置,方法是在其他代码之前编写以下代码行中的内容:

     ini_set("allow_url_fopen", true);

Make sure there are no redirects.确保没有重定向。

file_get_contents(php://input) doesn't pass the body content through redirects. file_get_contents(php://input)不会通过重定向传递正文内容。

One quick way to check for redirects is to check the url with curl.检查重定向的一种快速方法是使用 curl 检查 url。 On the command line: curl -IL http://example.com/api在命令行上: curl -IL http://example.com/api

I had got this error too, my solution is to change the data format to raw.我也有这个错误,我的解决方案是将数据格式更改为原始格式。

I get it from php doc where it says我从php doc那里得到它

php://input is not available with enctype="multipart/form-data" . php://input不适用于enctype="multipart/form-data"

for me this problem started, suddenly.对我来说,这个问题突然开始了。
i had installed ssl certificate.我已经安装了 ssl 证书。
when i checked the response code it showed me 301, then i realized and changed当我检查响应代码时,它向我显示了 301,然后我意识到并更改了
http:// http://
to
http s :// HTTP S://
and got all the request back with file_get_contents('php://input').并使用 file_get_contents('php://input') 取回所有请求。

in your example curl call:在您的示例 curl 调用中:
put s after http as shown below:将 s 放在 http 之后,如下所示:
curl -i -X PUT -d '{"address":"Sunset Boulevard"}' https://localhost/clients/ryan

I wrote a headerfile with this code:我用这段代码写了一个头文件:

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;
}

It checks for the correct content-type and it reads only as much post input, like specified in Content-Length header.它检查正确的内容类型,并且只读取与 Content-Length 标头中指定的一样多的帖子输入。 When receiving a valid JSON it created an global Array $_POST_JSON.当接收到有效的 JSON 时,它会创建一个全局数组 $_POST_JSON。

So you can work with your JSON-Content the similiar like you do it with url-encoded POST values.因此,您可以像使用 url 编码的 POST 值一样使用您的 JSON-Content。

Example:示例:

 echo $_POST_JSON["address"];
 // or
 echo $_REQUEST["address"];

I had the same problem.我有同样的问题。 Eventually, I found that the problem was that in the client side I didn't stringify the json object (previously I used nodejs server and it was OK).最终,我发现问题是在客户端我没有对json对象进行字符串化(之前我使用的是nodejs服务器,还可以)。 Once I did that, I received the data in $_POST (not as json), as regular parameters.一旦我这样做了,我就收到了 $_POST 中的数据(不是 json),作为常规参数。

The correct function call is:正确的函数调用是:

file_get_contents("php://input");

You should be getting an error message saying that php:input doesn't exist...您应该收到一条错误消息,指出php:input不存在...

In any case, PUT is intended for uploading files to the server, assuming the server supports it.在任何情况下, PUT都是为了将​​文件上传到服务器,假设服务器支持它。 Usually you'd use POST with a Content-Type header appropriate to the content.通常,您会使用带有适合Content-Type标头的POST

On Windows the combination of 'single "double" quotes' does not seem to work.在 Windows 上,“单“双”引号的组合似乎不起作用。 Use escape for quotes in your json data (as below) & it should work在您的 json 数据中使用转义引号(如下所示)并且它应该可以工作

curl -X PUT -d "{\"address\":\"Sunset Boulevard\"}" http://localhost/clients/ryan

Edit as you wish随心所欲编辑

function getPostObject() {
    $str = file_get_contents('php://input');
    $std = json_decode($str);
    if ($std === null) {
        $std = new stdClass();
        $array = explode('&', $str);
        foreach ($array as $parm) {
            $parts = explode('=', $parm);
            if(sizeof($parts) != 2){
                continue;
            }
            $key = $parts[0];
            $value = $parts[1];
            if ($key === NULL) {
                continue;
            }
            if (is_string($key)) {
                $key = urldecode($key);
            } else {
                continue;
            }
            if (is_bool($value)) {
                $value = boolval($value);
            } else if (is_numeric($value)) {
                $value += 0;
            } else if (is_string($value)) {
                if (empty($value)) {
                    $value = null;
                } else {
                    $lower = strtolower($value);
                    if ($lower === 'true') {
                        $value = true;
                    } else if ($lower === 'false') {
                        $value = false;
                    } else if ($lower === 'null') {
                        $value = null;
                    } else {
                        $value = urldecode($value);
                    }
                }
            } else if (is_array($value)) {
                // value is an array
            } else if (is_object($value)) {
                // value is an object
            }
            $std->$key = $value;
        }
        // length of post array
        //$std->length = sizeof($array);
    }
    return $std;
}

I see the problem,我看到了问题,

You need to add filename.php in the end of the request url or need to rewrite the server rules in .htaccess file to get around this.您需要在请求 url 的末尾添加 filename.php 或需要在 .htaccess 文件中重写服务器规则来解决这个问题。

curl -i -X PUT -d '{"address":"Sunset Boulevard"}' http://localhost/clients/ryan/{filename.php}

replace {filename.php} with appropriate file name.用适当的文件名替换 {filename.php}。 :) :)

{
  "action":"get_events_by_category",
  "category_id":2
}

Your row string data must be a Double quote "" not use single ''您的行字符串数据必须是双引号 "" 不能使用单个 ''

FWIW I was using Postman to send the values. FWIW 我正在使用 Postman 发送值。 On the Body tab I should have used the "Raw" tab to send the json {"ID":1234,"Type":"Blah"} but I was foolishly using the form-data tab to put in the Key/Value which made the php://input result in NULL.在正文选项卡上,我应该使用“原始”选项卡发送 json {"ID":1234,"Type":"Blah"} 但我愚蠢地使用表单数据选项卡放入键/值使 php://input 结果为 NULL。 Once I switched to using the raw tab with the JSON then all worked as expected.一旦我切换到使用带有 JSON 的原始选项卡,那么一切都按预期工作。

{"id": 1, "username":"surecoder", "password":"surecoder"}

Your key and value strings data must be a Double quote "" not use single ''您的键和值字符串数据必须是双引号 "" 而不是单引号 ''

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM