PHP - Posting JSON via file_get_contents

Ben picture Ben · Jul 3, 2012 · Viewed 36.2k times · Source

I am trying to POST JSON content to a remote REST endpoint, however the 'content' value appears to be empty on delivery. All other headers etc are being received correctly, and the web service tests successfully with a browser based test client.

Is there a problem with my syntax below where I specify the 'content' field?

$data = array("username" => "duser", "firstname" => "Demo", "surname" => "User", "email" => "[email protected]");   
$data_string = json_encode($data);

$result = file_get_contents('http://test.com/api/user/create', null, stream_context_create(array(
'http' => array(
'method' => 'POST',
'header' => array('Content-Type: application/json'."\r\n"
. 'Authorization: username:key'."\r\n"
. 'Content-Length: ' . strlen($data_string) . "\r\n"),
'content' => $data_string)
)
));

echo $result;

Answer

Bob Davies picture Bob Davies · Jul 3, 2012

This is the code I always use and it looks pretty similar (though this is of course for x-www-form-urlencoded). Perhaps your username:key needs to be base64_encode'd.

function file_post_contents($url, $data, $username = null, $password = null)
{
    $postdata = http_build_query($data);

    $opts = array('http' =>
        array(
            'method'  => 'POST',
            'header'  => 'Content-type: application/x-www-form-urlencoded',
            'content' => $postdata
        )
    );

    if($username && $password)
    {
        $opts['http']['header'] = ("Authorization: Basic " . base64_encode("$username:$password"));
    }

    $context = stream_context_create($opts);
    return file_get_contents($url, false, $context);
}