Michael Rennison Michael Rennison - 2 months ago 7
PHP Question

Setting correct content type for cURL to recieve a response

I'm trying to create a relatively simple php endpoint for users to send requests to. I know that the endpoint is working because when I accessed it using cURL the parameters I sent to my database we're added. The problem however is that when I use

var_dump($response);


The page returns "NULL".

So the code is working fine, I just want to know how to get it the print an error/success message

This is what I've tried so far on the endpoint

header("HTTP/1.1 200 OK");
header('Content-Type: text/plain');
echo 'Success message';


the full cURL code is this

$curl = curl_init();
curl_setopt_array($curl, array(
CURLOPT_RETURNTRANSFER => 1,
CURLOPT_URL => $url,
CURLOPT_POSTFIELDS => 'example=this'
));
$resp = curl_exec($curl);
// Close request to clear up some resources
curl_close($curl);
$response = json_decode($resp, true);
var_dump($response);


So how can I get the success message to properly show instead of "NULL"?

Answer

Test if your curl code returns something by testing: var_dump($resp). It looks like NULL comes from json_decode. You are not returning valid JSON from the endpoint.

php > var_dump(json_decode("Success message", true));
NULL

Try returning a json string such as:

php > echo json_encode("Success", true);
"Success"

Note the " around it. This encodes a json string. See the JSON spec for a reference on how to encode json. Best practice, if your return json, then run your content through json_encode().

Your curl code seems correct.