Home > Enterprise >  cURL php POST error header when send data with JSON
cURL php POST error header when send data with JSON

Time:09-22

i'm trying to post data with cURL with JSON data and i've changed the header but i got error, here is my code

public static function curlValidation($url, $params) {
    $ch = curl_init();

    curl_setopt($ch,CURLOPT_URL, $url);
    curl_setopt($ch,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($ch,CURLOPT_HEADER, array("Accept:application/json", "Content-Type:application/json"));
    curl_setopt($ch,CURLOPT_POST, true);
    curl_setopt($ch,CURLOPT_POSTFIELDS, $params);

    $result = curl_exec($ch);
    if($result === false)
        return curl_error($ch);

    curl_close($ch);
    return $result;
}

$params value is JSON

{
   "NIK":"123",
   "NAMA":"ASD",
   "TGL_LHR":"123",
}

and got error like this

'HTTP/1.1 500 Internal Server Error
Server: Apache-Coyote/1.1
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: PUT, GET, POST, DELETE, OPTIONS
Access-Control-Allow-Headers: origin, x-requested-with, content-type
Content-Type: application/json;charset=UTF-8
Transfer-Encoding: chunked
Date: Mon, 20 Sep 2021 02:07:58 GMT
Set-Cookie: SRVNAME=app05-nutanix; path=/

{\"msg\":\"Content type \'application/x-www-form-urlencoded;charset=UTF-8\' not supported\",\"error\":false}'

CodePudding user response:

The reason this does not work is because you have an error with this line:

curl_setopt($ch,CURLOPT_HEADER, array("Accept:application/json", "Content-Type:application/json"));

The constant you should use is CURLOPT_HTTPHEADER

CodePudding user response:

Try to do this inside your function - I think your headers data is corrupted:

$ch = curl_init();

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $params);

$headers = array();
$headers[] = 'Content-Type: application/json';
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);

$result = curl_exec($ch);
if (curl_errno($ch)) {
    echo 'Error:' . curl_error($ch);
}
curl_close($ch);

According to the message you receive it says that you are sending the wrong content type.

Replace the curl lines in your function with these or just the $headers line of yours with these 3 $headers lines from this example.

  • Related