2

It seems that Content-Type: application/x-www-form-urlencoded just hacked my curl result

I have a curl request below

curl -k -X POST \
  --header "Content-Type: application/x-www-form-urlencoded" \
  --header "Accept: application/json" \
  --data-urlencode "grant_type=naco:pdata:params" \
  --data-urlencode "apikey=<apikey>" \
  "https://api_endpoint"

Here is how I successful post data and get response as expected. Here is the succesful result

{
  "product_id": "101",
  "product_name": "Television"

}

Now when I echoed or var_dump the result ($res) as per code below then $res is empty and as such, product_name and product_id cannot be printed and yet am having my result response on the page displayed.

I now discovered that it was the Content-Type: application/x-www-form-urlencoded that forces the result to be displayed via header but cannot allow $res response to echo the result.

Please how do Print product_id and product_name

$header= array(                                                                          
 'Content-Type: application/x-www-form-urlencoded',                                                                               
    "Accept: application/json");                                                                       

$builder= http_build_query([
   'grant_type'=>"naco:pdata:params", 
    'apikey'=>"xxxxxxx"]);



$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api_endpoint");
curl_setopt($ch, CURLOPT_POSTFIELDS, $builder);

curl_setopt($ch, CURLOPT_HTTPHEADER, $header);  
curl_setopt($ch, CURLOPT_CUSTOMREQUEST,'POST');

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER,false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,false);

 $res = curl_exec($ch);

curl_close($ch);

//code below shows empty result and yet i can still see the result response on the page

echo $res
var_dump($res);
$json = json_decode($res, true);
echo $product_name = $json['product_name'];
echo $product_id = $json['product_id'];
chinazaike
  • 517
  • 6
  • 19

0 Answers0