Search code examples
phpcurlhttp-headersphp-curl

cURL php POST error header when send data with JSON


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}'

Solution

  • 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