Search code examples
phpcurlpostmanlibcurlphp-curl

I am not getting expected response from Curl request in PHP


I have a curl request which is working fine in https://reqbin.com/ and in the Postman but when I implement same in PHP it is not working; Below is plain CURL command;

curl -X POST \
'http://example.com' \
-H 'content-type: application/json' \
-d '{"Header": {"Token": "xyz"}, "Body": {"Email": "abc@gmail.com", "FirstName": "test", "Surname": "test"}}'

The response I am getting from this is;

{"Header":{"Status":"OK"},"Body":{"BackUrl":"https:example.com","Redirect":"YES"}}

But when I implement same in PHP as;

$curl = curl_init();
$headers = array(
    "content-type: application/json"
);

$postData = '{"Header": {"Token": "xyz"}, "Body": {"Email": "abc@gmail.com",  "FirstName": "test", "Surname": "test"}}';

$opt_arr = array(
    CURLOPT_URL => 'http://example.com',
    CURLOPT_RETURNTRANSFER => true,
    CURLOPT_ENCODING => '',
    CURLOPT_MAXREDIRS => 10,
    CURLOPT_TIMEOUT => 0,
    CURLOPT_FOLLOWLOCATION => true,
    CURLOPT_CUSTOMREQUEST => 'POST',
    CURLOPT_POST => true,
    CURLOPT_HTTPHEADER => $headers,
    CURLOPT_POSTFIELDS => $postData
);
curl_setopt_array($curl, $opt_arr);
echo $resp = curl_exec($curl);
curl_close($curl);

I do not receive the expected response;

{"Header":{"Status":"ERROR","ErrorMsg":"INVALID_REQUEST"},"Body":{"BackUrl":"","Redirect":"NO"}}

I need help converting the above working curl to the correct PHP code.


Solution

  • After many unsuccessful attempts in PHP, I tried to implement it in javascript and here I got to know that error is with SSL security, hence I added HTTPS into the URL, and it worked.

    $curl = curl_init();
    $headers = array(
        "content-type: application/json"
    );
    
    $postData = '{"Header": {"Token": "xyz"}, "Body": {"Email": "abc@gmail.com",  "FirstName": "test", "Surname": "test"}}';
    
    $opt_arr = array(
        CURLOPT_URL => 'https://example.com',
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_ENCODING => '',
        CURLOPT_MAXREDIRS => 10,
        CURLOPT_TIMEOUT => 0,
        CURLOPT_FOLLOWLOCATION => true,
        CURLOPT_CUSTOMREQUEST => 'POST',
        CURLOPT_POST => true,
        CURLOPT_HTTPHEADER => $headers,
        CURLOPT_POSTFIELDS => $postData
    );
    curl_setopt_array($curl, $opt_arr);
    echo $resp = curl_exec($curl);
    curl_close($curl);