php - 406 error when sendingreceiving JSON data - Stack Overflow

时间: 2025-01-06 admin 业界

I have tried several options found here on StackOverflow but haven't been able to get my code working. Thinking it was just something strange in my code, I created a couple basic scripts just to test it out. I get a 406 error and I have no idea why...

send.php

$url = (empty($_SERVER['HTTPS']) ? 'http' : 'https') . "://".$_SERVER['HTTP_HOST'].str_replace(realpath($_SERVER['DOCUMENT_ROOT']), '', realpath(__DIR__))."/receive.php"; 
$data = array(
    'first_name' => "Bart",
    'last_name' => "Simpson",
);

$return_data=json_encode($data);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json', 'Content-Type: application/json'));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FAILONERROR, true); // Required for HTTP error codes to be reported via our call to curl_error($ch)
curl_setopt($ch, CURLOPT_POSTFIELDS, $return_data);
$resp = curl_exec($ch);
if (curl_errno($ch)) {
    $ch_error_msg = curl_error($ch);
    echo "ERROR:".$ch_error_msg;
    exit;
}
curl_close($ch);

$result = json_decode($resp);
echo "<pre>".var_export($result,true)."<pre>";

receive.php

$response = file_get_contents('php://input');
$data = json_decode($response, true);
$data_display = var_export($data, true); // Nice readable view of array

if (isset($data['first_name']) && $data['first_name']!="")
{
        http_response_code(200);
        header("Content-Type:application/json");
        $return_data["http_status_code"]="200";
        $return_data["http_status_desc"]="OK";
        echo json_encode($return_data);
        exit;
}
else
{
        http_response_code(400);
        header("Content-Type:application/json");
        $return_data["http_status_code"]="400";
        $return_data["http_status_desc"]="Required data not supplied";
        echo json_encode($return_data);
        exit;
}

Why do I get a 406 error?