2

We're having problems with an api we are using.

Here is the code we're using (naming no names on the api front)

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://apiurl.com/whatever/api/we/call');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$ch_output = curl_exec($ch);
curl_close($ch);

This response times out, but not for ages. This is hideously slowing down our web app, and as such further code breaks because of the bad return value. This I can fix, however the response timeout I don't know how to fix. Is there any way to quickly see if a url is "responding" (e.g. something like ping in terminal) before trying to do a curl request?

Thank you.

2
  • 1
    But even if you ping it succesfully the second after that it might not respond. Commented Feb 17, 2012 at 20:20
  • Ping has nothing to do here. It can be that ping is present and site is unreachable and vice-versa. And besides - you cannot ping url - only hostnames. Commented Feb 17, 2012 at 20:26

2 Answers 2

3

Do you mean usingcurl_setopt($ch,CURLOPT_CONNECTTIMEOUT,NUMERIC_TIMEOUT_VALUE);to set the timeout?

Sign up to request clarification or add additional context in comments.

4 Comments

Also see CURLOPT_TIMEOUT in case connection happens, but response stalls.
I haven't used that flag so its at the default timeout, whatever that might be. What would be a reasonable timeout value for an api? At the moment the script takes a good minute or so to bother to bail... we really need to cut that down to instant really. What would you use? Is something like 400ms too short? Too long?
You could give it a few seconds, and if it times out, cache that fact for a while. This way other scripts can just do a fast check using your local cache to see if the api was recently unusable. I think 400ms is short, because every so often a dns lookup needs to be performed, and those can easily take 400ms alone, but maybe you're ok with a once in a while false timeout.
Thanks for the info chris. :) How would I know if it has timed out? Would it be if the response is blank?
2

Your best option would be to set the timeout on curl to a more acceptable level. There are several timeout options available for DNS lookup, connect timeout, transfer timeout, etc. More information is available here http://php.net/manual/en/function.curl-setopt.php

Comments

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.