0

I am able to successfully make a send POST values through CURL but I can't seem to figure out how to get the only the JSON code it returns.

Here is a part of my code:

try {
    $curl = curl_init($url);

    if (FALSE === $curl)
        throw new Exception('failed to initialize');

    curl_setopt($curl, CURLOPT_HEADER, 1);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_HTTPHEADER,
        array("Content-type: application/json")
    );          
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
    curl_setopt($curl, CURLOPT_CUSTOMREQUEST, "POST");   
    curl_setopt($curl, CURLOPT_POSTFIELDS, json_encode($data));

    $message = curl_exec($curl);

    if (FALSE === $message)
        throw new Exception(curl_error($curl), curl_errno($curl));

    $response = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    $error = $message;

    var_dump($error);
    curl_close($curl);

} catch(Exception $e) {
    trigger_error(
        sprintf(
            'Curl failed with error #%d: %s',
            $e->getCode(), $e->getMessage()
        ),
        E_USER_ERROR
    );
}

I am able to get the correct value for the $response variable but the returned message gives me:

string(253) "HTTP/1.1 400 Bad Request Cache-Control: no-cache Pragma: no-cache Content-Type: application/json; charset=utf-8 Expires: -1 Server: Microsoft-IIS/8.5 Date: Sun, 02 Jul 2017 17:47:34 GMT Content-Length: 38 {"Message":"Email is already in used"}"

when I try to use var_dump. What I am aiming to store for me error message variable it the value for Message that is in {"Message":"Email is already in used"}

Any tips?

Thanks so much!

2
  • Have you tried to json encode after the cURL has been executed? Commented Jul 2, 2017 at 18:04
  • "400 Bad Request" suggests to me that the server is not processing your request because of a client error. Does the endpoint definitely accept POST requests? Does the $data variable contain all required fields? Commented Jul 2, 2017 at 18:04

1 Answer 1

3
HTTP/1.1 400 Bad Request Cache-Control: no-cache Pragma: no-cache Content-Type: application/json; charset=utf-8 Expires: -1 Server: Microsoft-IIS/8.5 Date: Sun, 02 Jul 2017 17:47:34 GMT Content-Length: 38

Are the headers returned by the cURL request.
You'll have to set CURLOPT_HEADER to FALSE (0) to remove the headers from the output:

curl_setopt($curl, CURLOPT_HEADER, 0);

As stated by the documentation when CURLOPT_HEADER is TRUE headers will be included in the output.

Sign up to request clarification or add additional context in comments.

1 Comment

Ahhhh this is such a small detail I missed. Thanks a lot!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.