Michael Rennison Michael Rennison - 27 days ago 4x
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


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_URL => $url,
CURLOPT_POSTFIELDS => 'example=this'
$resp = curl_exec($curl);
// Close request to clear up some resources
$response = json_decode($resp, true);

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


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));

Try returning a json string such as:

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

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.