Alex
Alex

Reputation: 5685

JSON over cURL in PHP not working

I have the pages below.

Page json.php:

$json_data = array(
    'first_name' => 'John',
    'last_name'  => 'Doe',
    'birthdate'  => '12/02/1977',
    'files'      => array(
        array(
            'name'   => 'file1.zip',
            'status' => 'good'
        ),
        array(
            'name'   => 'file2.zip',
            'status' => 'good'
        )
    )
);

$url = 'http://localhost/test.php';

$content = json_encode($json_data);

$curl = curl_init();

curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_HEADER, false);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_HTTPHEADER,
    array(
        "Content-type: application/json",
        "Content-Length: " . strlen($content)
    )
);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, 'json=' . urlencode($content));
curl_setopt($curl, CURLINFO_HEADER_OUT, true);

$json_response = curl_exec($curl);

$status      = curl_getinfo($curl, CURLINFO_HTTP_CODE);
$header_sent = curl_getinfo($curl, CURLINFO_HEADER_OUT);

curl_close($curl);

echo $header_sent;
echo '<br>';
echo $status;
echo '<br>';
echo $json_response;

Page test.php:

echo '<pre>';
print_r($_POST);
echo '</pre>';

When I’m calling json.php from the browser, I get the following result:

POST /json.php HTTP/1.1 Host: localhost Accept: */* Content-type: application/json Content-Length: 150
200

Array
(
)

Why can’t I see the POST string I’m trying to send?

Edit:

If I don’t set the Content-type: application/json header (as per @landons’s comment), I get the following result:

POST /ddabvd/widendcm/widendcm-finished.php HTTP/1.1 Host: localhost Accept: */* Content-Length: 150 Content-Type: application/x-www-form-urlencoded 
200
Array
(
    [json] => {"first_name":"John","last_name":"Doe","birthdate":"12\/02\/1977","files":[{"name":
)

Upvotes: 1

Views: 478

Answers (1)

Sven
Sven

Reputation: 70863

PHP does not use it's internal request parsing for POST requests if the content type is not set to one of the two official content types that are used when posting forms from inside a browser. (e.g. the only allowed content types are multipart/form-data, often used for file uploads, and the default value application/x-www-form-urlencoded).

If you want to use a different content-type, you are on your own, e.g. you have to do all the parsing yourself when fetching the request body from php://input.

In fact, your content type is currently wrong. It is NOT application/json, because the data reads json={...}, which is incorrect when being parsed as json.

Upvotes: 2

Related Questions