2

I'm using the code below to query an api however I'm not seeing any output. The header is returned however I also get an error - "An error has occurred:" with nothing else - not very helpful to say the least. Does anyone know what I'm doing wrong here? (NB I've had to remove the user details for obvious reasons)

//Required Call Information;
$username = "xxxxxxxxxxxxx";
$password = "xxxxxxxxxxxxxxxxxxxxxxxxxx";
$remote_url = 'https://xxxxxxxxxxxxx.com/xx.json';


// init the resource
$ch = curl_init();

//Header Information;
$headr = array();
$headr[] = "Authorization: Basic " . base64_encode("$username:$password");
$headr[] =  "X-Page:" . $pages;

// set curl options
curl_setopt($ch, CURLOPT_URL,$remote_url);
curl_setopt($ch, CURLOPT_HTTPHEADER,$headr);
curl_setopt($ch, CURLOPT_HEADER, true);

// execute
$output = curl_exec($ch);

// echo
echo $output;

// echo
print $output;

// free
curl_close($ch);

// check status of server being called vis crul
var_dump(curl_getinfo($ch));

//if error
if (!curl_exec($ch)) {
    // if curl_exec() returned false and thus failed
    echo 'An error has occurred: ' . curl_error($ch);
}
else {
    echo 'everything was successful';
}
3
  • Is the error you are getting a PHP fatal error or exception? Commented Feb 12, 2016 at 2:59
  • You need to set the CURLOPT_RETURNTRANSFER opt for curl_exec() to return the result. Commented Feb 12, 2016 at 4:33
  • Also, when doing if ( ! curl_exec(...) ), you're doing another call to the URL. Better use if ( $output === FALSE ). Commented Feb 12, 2016 at 4:36

2 Answers 2

2

Adding the RETURN_TRANSFER curl opt will return data rather than a boolean when $output = curl_exec($ch); is called.

curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for this, fyi it turns out i also needed to add curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true); to allow CURL to follow the redirect and retrieve information.
I am still getting An error has occurred though i have added curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
faisal1208 - maybe try setting curl_setopt($ch,CURLOPT_FAILONERROR,true); which may help with any errors. Also, check the HTTP response code as you might be getting a 404 or another error.
0

Add in the following curl opt and see what you get back:

curl_setopt($ch, CURLOPT_VERBOSE, true);

1 Comment

Hey J_D, thanks for the input, I've just tried this and unfortunately this doesn't change anything, I still get an error without an error message.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.