issues of CURL to call rest api.

General discussion on PHP
Post Reply
Posts: 1
Joined: Fri Apr 27, 2018 6:47 pm

issues of CURL to call rest api.

Post by mark5973 » Fri Apr 27, 2018 6:53 pm

I try to use PHP CURL to call REST API(API URL is good for I can access josn data from browser), the Codes are:


$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HEADER, false);
curl_setopt($ch, CURLOPT_RETURNTRANSFER,true);
curl_setopt($ch, CURLOPT_TIMEOUT, 5);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);

$ret = curl_exec($ch);
if($ret == false)
$retinfo = curl_getinfo($ch);

$data = json_decode($ret, true);

I find Http_code = 301, it means redirection happens so I add this:

curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);

But I get Http_code = 404 and pages not found, it redirects to another invalid page,

How can I get right json data through curl just as opened from browser?

User avatar
Posts: 285
Joined: Thu Jan 22, 2009 3:16 pm

Re: issues of CURL to call rest api.

Post by zend_eyalt » Mon May 07, 2018 12:54 pm

AFAIK, CURLOPT_FOLLOWLOCATION which you've mentioned should do the trick.

Are you sure that the redirected page actually exists ? maybe try to test your code VS a simple controllable redirect as in:

Code: Select all


function Redirect($url, $statusCode=301) {
	header('Location: ' . $url, true, $statusCode);

Redirect('', 301);

Post Reply