Running this code in cURL gives me JSON data :
curl -X POST -H "Content-Type: application/json" -d '{"fund_id":"74","product_id":"22","from_date":"2017-01-01","to_date":"2022-01-12"}' https://api.hdfclife.com/api/funds/get-fund-nav
But when using curl in php I receive NULL as data :
$url = "https://api.hdfclife.com/api/funds/get-fund-nav";
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$headers = array(
"Content-Type: application/json",
);
curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
$data = '{"fund_id":"74","product_id":"22","from_date":"2017-01-01","to_date":"2022-01-12"}';
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
//for debug only!
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
$resp = curl_exec($curl);
curl_close($curl);
var_dump($resp);
?>
What am I doing wrong here? Also I am new to PHP so please go easy on me.
CodePudding user response:
It seems that the URL that you're calling is moved permanently and it redirects the request in itself and returns status code "301 Moved Permanently". CURL in php doesn't support the redirects by default and options must be declared for CURL in order to support it. Just add the following code to your CURL options and it should work just fine.
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_POSTREDIR, 3);
