I have a zip code lookup service and I'm worried about any possible timeouts or the server being down.
If I don't get any HTTP Response after 20-25s of the initial request I would want to respond with a JSON signifying it failed:
({ success:0 })
I have a zip code lookup service and I'm worried about any possible timeouts or the server being down.
If I don't get any HTTP Response after 20-25s of the initial request I would want to respond with a JSON signifying it failed:
({ success:0 })
You can set timeout (and a lot of other options) for file_get_contents()
as well using stream_context_create(). See here for a list of options.
Modified example from the manual:
<?php
$opts = array(
'http'=>array(
'timeout' => 25,
'method'=>"GET",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
/* Sends an http request to www.example.com
with additional headers shown above */
$contents = file_get_contents("http://example.com", false, $context);
?>
If that works for you, I see nothing speaking against using cURL over this.
cURL has a lot more features and it'll probably be more useful in your case.
You can use this
curl_setopt($ch, CURLOPT_TIMEOUT, 40); //enter the number of seconds you want to wait
Your title and your question text pose two different questions. Both cURL and file_get_contents can use a timeout with a specific return.
If you use cURL, you can set the timeout using curl_setopt($ch, CURLOPT_TIMEOUT, 25) //for 25s
.
To set the timeout for file_get_contents you have to include it in your context.
$opts = array(
'http'=>array(
'method'=>"GET",
'timeout'=>"25",
'header'=>"Accept-language: en\r\n" .
"Cookie: foo=bar\r\n"
)
);
$context = stream_context_create($opts);
// Open the file using the HTTP headers set above
$file = file_get_contents('http://www.example.com/', false, $context);
Note however that file_get_contents, unlike cURL, has a default timeout (found in the option default_socket_timeout).
Both cURL and file_get_contents return FALSE
on a failed transfer, so catching a failure is easy.