我应该使用file_get_contents或curl进行Web服务请求吗?

时间:2010-03-19 16:20:05

标签: php web-services

我有邮政编码查询服务,我担心任何可能的超时或服务器停机。

如果我在初始请求的20-25之后没有得到任何HTTP响应,我想用JSON回复,表示它失败了:

({ success:0 })

3 个答案:

答案 0 :(得分:6)

您可以使用stream_context_create()file_get_contents()设置超时(以及许多其他选项)。有关选项列表,请参阅here

手册中的修改示例:

<?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);
?>

如果这对您有用,我认为没有人反对使用cURL。

答案 1 :(得分:1)

您的标题和问题文字提出了两个不同的问题。 cURL和file_get_contents都可以使用具有特定返回的超时。

如果您使用cURL,则可以使用curl_setopt($ch, CURLOPT_TIMEOUT, 25) //for 25s设置超时。

要设置file_get_contents的超时,您必须将其包含在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);

但请注意,与cURL不同,file_get_contents具有默认超时(可在default_socket_timeout选项中找到)。

cURL和file_get_contents都会在失败的传输中返回FALSE,因此很容易发现故障。

答案 2 :(得分:0)

cURL具有更多功能,在您的情况下它可能更有用。

你可以使用这个 curl_setopt($ch, CURLOPT_TIMEOUT, 40); //enter the number of seconds you want to wait

相关问题