PHP cURL:CURLOPT_CONNECTTIMEOUT 对比 CURLOPT_TIMEOUT

PHP cURL: CURLOPT_CONNECTTIMEOUT vs CURLOPT_TIMEOUT

PHP 有两个与超时相关的选项:CURLOPT_CONNECTTIMEOUTCURLOPT_TIMEOUT.

PHP 网站上的描述有点含糊。有什么区别?

使用一个真实世界的例子:假设你通过 cURL 发送 GET vars 到 URL 并且你想收到一个 XML 返回, CURLOPT_CONNECTTIMEOUT 与连接到服务器可能花费的最长时间和 CURLOPT_TIMEOUT 发送回 XML 可能花费的最长时间有关?

CURLOPT_CONNECTTIMEOUT is the maximum amount of time in seconds that is allowed to make the connection to the server. It can be set to 0 to disable this limit, but this is inadvisable in a production environment.

CURLOPT_TIMEOUT is a maximum amount of time in seconds to which the execution of individual cURL extension function calls will be limited. Note that the value for this setting should include the value for CURLOPT_CONNECTTIMEOUT.

In other words, CURLOPT_CONNECTTIMEOUT is a segment of the time represented by CURLOPT_TIMEOUT, so the value of the CURLOPT_TIMEOUT should be greater than the value of the CURLOPT_CONNECTTIMEOUT.

来自Difference between CURLOPT_CONNECTTIMEOUT and CURLOPT_TIMEOUT

CURLOPT_CONNECTTIMEOUT不是CURLOPT_TIMEOUT

所代表的时间段

如果 CURLOPT_CONNECTTIMEOUT 设置为 3 秒,CURLOPT_TIMEOUT 设置为 4 秒,则执行最多可能需要 7 秒。

我通过模拟慢速服务器连接(iptables 下降)测试了这个。

除了

根据source code设置连接:如果两者都设置,则使用最严格的。但仅限于连接阶段。

/* if a timeout is set, use the most restrictive one */

  if(data->set.timeout > 0)
    timeout_set |= 1;
  if(duringconnect && (data->set.connecttimeout > 0))
    timeout_set |= 2;

  switch(timeout_set) {
  //...
  case 3:
    if(data->set.timeout < data->set.connecttimeout)
      timeout_ms = data->set.timeout;
    else
      timeout_ms = data->set.connecttimeout;
    break;

Unit tests 来源

CURLOPT_CONNECTTIMEOUT是只连接服务器的时间

CURLOPT_TIMEOUT 是整个连接时间加上交换数据的时间。

因此,CURLOPT_TIMEOUT 总是包含 CURLOPT_CONNECTTIMEOUT。

验证使用 CURLINFO_CONNECT_TIME 和 CURLINFO_TOTAL_TIME 非常容易。

  • curl_getinfo($ch, CURLINFO_CONNECT_TIME) 获取信息并且 curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $yourMaxConnTime) 设置最大要连接的值。

  • curl_getinfo($ch, CURLINFO_TOTAL_TIME) 获取信息并 curl_setopt($ch, CURLOPT_TIMEOUT, $yourMaxTotTime) 设置最大值整个操作的价值。

当然,$yourMaxTotTime 必须始终高于 $yourMaxConnTime。 所有这些值都以秒为单位。

接受的答案不正确。请参阅 Everything CURL 文档以获取正确的文档。
.. 基本上连接时间涵盖建立http连接的两个方面:

  • DNS 解析
  • 建立 tcp 连接之前的时间。

CURLOPT_TIMEOUT 或 CURLOPT_TIMEOUT_MS 选项根本不涵盖这段时间。这些涵盖了我们开始通过刚刚在连接阶段建立的 TCP 连接讨论 HTTP 之后发生的所有事情。

这种区别给很多人带来了问题,但它确实允许设置一个相对较短的连接超时,因为如果服务器完全不可用,为什么还要等待呢?然而,您仍然可以将请求超时设置得相当长,以防服务的预期响应时间难以预测。

一般来说,对于生产设置,CURLOPT_CONNECTION_TIMEOUT 应该少于 5 秒并且 CURLOPT_TIMEOUT 应该尽可能短(不会导致您经常丢弃请求)。