0

I’m trying to send some JSON data over POST with fopen, using the function below.

function doPostRequest($url, $data, $optional_headers = null)
{
    $params = array(
        'http' => array(
            'method'  => 'POST',
            'content' => $data,
            'header'  => 'Content-type: application/json' . "\r\n"
                       . 'Content-Length: ' . strlen($data) . "\r\n"
        )
    );

    if ($optional_headers !== null) {
        $params['http']['header'] = $optional_headers;
    }

    $ctx = stream_context_create($params);

    try {
        $fp = fopen($url, 'rb', false, $ctx);

        $response = stream_get_contents($fp);
    } catch (Exception $e) {
        echo 'Exception: ' . $e->getMessage ();
    }

    return $response;
}

$json_data = array(
    'first_name' => 'John',
    'last_name'  => 'Doe'
);

$content = urlencode(json_encode($json_data));

doPostRequest($url, $content);

I don’t get any error, but when I’m trying to decode the data, $input_stream is empty. Why? What am I missing?

$input_stream = file_get_contents('php://input');
$json = urldecode($input_stream);
var_dump($input_stream);

Edit: I should mention that the code works on a machine with XAMPP installed, but it doesn’t on another one. Could the server configuration have anything to do with it?

Alex
  • 5,565
  • 6
  • 36
  • 57

2 Answers2

0

I believe that the reason is because of the way you are encoding your data and setting your Content-type.

If you want to send it with Content-type: application/json don't urlencode the data.

See here for differences between application/json and application/x-www-form-urlencoded.

Community
  • 1
  • 1
BPaasch
  • 154
  • 4
  • Even without `urlencode` I get the same result: `$input_stream` is empty. – Alex Apr 03 '13 at 19:00
  • @Alex Instead of doing *var_dump($input_stream);* try doing *echo $input_stream;* – BPaasch Apr 03 '13 at 20:07
  • @Alex I tried it by copying your data exactly except I had to specify the *url* and also I changed it from *var_dump($input_stream);* to log it to a file: *error_log('inputstream---'.$input_stream."----\n", 3, '/usr/local/lib/php/logs/php_error.log');* and I get *inputstream---%7B%22first_name%22%3A%22John%22%2C%22last_name%22%3A%22Doe%22%7D----* as my output. – BPaasch Apr 03 '13 at 20:25
  • I just realized that this code works as well on a different machine with XAMPP installed, so I was wondering: could be a config issue? – Alex Apr 03 '13 at 20:37
0

The problem was the fact that $content from doPostRequest($url, $content); was not UTF-8 encoded and there were some strange characters, therefore json_decode was breaking.

As per json_decode man:

This function only works with UTF-8 encoded strings.

Alex
  • 5,565
  • 6
  • 36
  • 57