Question

[Solved] file_get_contents(‘php://input’) always returns an empty string

I’m building a PHP RESTful API, following this tutorial. The following function, which should return the data sent with the request when the ‘put’ method is used, returns null every time:

file_get_contents('php://input').

I’ve even downloaded and tested the full code example in the tutorial and it still returns null.

I’m using cURL and the following command in order to test the ‘put’ method:

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. What am I doing wrong?

Enquirer: Igor

||

Solution #1:

As noted elsewhere on the web, php://input content does not get through if request is redirected. 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. Check your web server logs to verify this, and act accordingly to avoid the redirection when making calls to the web service.

Respondent: Igor

Solution #2:

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:

  1. the curl url you used, make sure that url is actually working and not returning errors.
  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.
  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)
  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.
  5. remember, file_get_contents only works when allow_url_fopen is set to true in your PHP settings. 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:

    ini_set("allow_url_fopen", true);
    

Solution #3:

Make sure there are no redirects.

file_get_contents(php://input) doesn’t pass the body content through redirects.

One quick way to check for redirects is to check the url with curl. On the command line:
curl -IL http://example.com/api

Respondent: Kristian

Solution #4:

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://input is not available with enctype=”multipart/form-data”.

Respondent: billrichards

Solution #5:

for me this problem started, suddenly.
i had installed ssl certificate.
when i checked the response code it showed me 301, then i realized and changed
http://
to
https://
and got all the request back with file_get_contents(‘php://input’).

in your example curl call:
put s after http as shown below:
curl -i -X PUT -d '{"address":"Sunset Boulevard"}' https://localhost/clients/ryan

Respondent: Timtcng.sen

Solution #6:

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.
When receiving a valid JSON it created an global Array $_POST_JSON.

So you can work with your JSON-Content the similiar like you do it with url-encoded POST values.

Example:

 echo $_POST_JSON["address"];
 // or
 echo $_REQUEST["address"];
Respondent: sifr_dot_in

Solution #7:

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).
Once I did that, I received the data in $_POST (not as json), as regular parameters.

Respondent: Radon8472

Solution #8:

The correct function call is:

file_get_contents("php://input");

You should be getting an error message saying that php:input doesn’t exist…

In any case, PUT is intended for uploading files to the server, assuming the server supports it. Usually you’d use POST with a Content-Type header appropriate to the content.

Respondent: Shlomo

Solution #9:

On Windows the combination of ‘single “double” quotes’ does not seem to work. Use escape for quotes in your json data (as below) & it should work

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

Solution #10:

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;
}
Respondent: sambha

Solution #11:

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.

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

replace {filename.php} with appropriate file name. 🙂

Respondent: Shanaka Madusanka

Solution #12:

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

Your row string data must be a Double quote “” not use single ”

Respondent: Mandan Sharma

Solution #13:

FWIW I was using Postman to send the values. 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. Once I switched to using the raw tab with the JSON then all worked as expected.

Respondent: kishan maru

The answers/resolutions are collected from stackoverflow, are licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0 .

Most Popular

To Top
India and Pakistan’s steroid-soaked rhetoric over Kashmir will come back to haunt them both clenbuterol australia bossier man pleads guilty for leadership role in anabolic steriod distribution conspiracy