file_get_contents()是否有超时设置?

Flo*_*ton 141 php timeout file-get-contents

file_get_contents()在循环中使用该方法调用一系列链接.每个链接可能需要15分钟以上才能处理.现在,我担心PHP是否file_get_contents()有超时期限?

如果是,它将超时通话并转到下一个链接.如果没有事先完成,我不想打电话给下一个链接.

那么,请告诉我是否file_get_contents()有超时期限.包含的文件file_get_contents()设置set_time_limit()为零(无限制).

ste*_*ewe 278

默认超时由default_socket_timeoutini-setting定义,即60秒.您也可以动态更改它:

ini_set('default_socket_timeout', 900); // 900 Seconds = 15 Minutes
Run Code Online (Sandbox Code Playgroud)

另一种设置超时的方法是使用stream_context_create将超时设置为正在使用的HTTP流包装器的HTTP上下文选项:

$ctx = stream_context_create(array('http'=>
    array(
        'timeout' => 1200,  //1200 Seconds is 20 Minutes
    )
));

echo file_get_contents('http://example.com/', false, $ctx);
Run Code Online (Sandbox Code Playgroud)

  • default_socket_timeout,stream_set_timeout和stream_context_create timeout是每行读/写的超时,而不是整个连接超时. (14认同)
  • 这个东西不是很完美,如果你的价值是1200,它实际上是2400.我只是测试它. (11认同)
  • 您能否提供有关如何为https url设置超时的信息? (8认同)

Ran*_*ell 30

正如@diyism所提到的," default_socket_timeout,stream_set_timeout和stream_context_create超时是每行读/写的超时,而不是整个连接超时. "@ step的最佳答案让我失望.

作为使用的替代方法file_get_contents,您始终可以使用curl超时.

所以这是一个适用于调用链接的工作代码.

$url='http://example.com/';
$ch=curl_init();
$timeout=5;

curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $timeout);

$result=curl_exec($ch);
curl_close($ch);
echo $result;
Run Code Online (Sandbox Code Playgroud)

  • 这个答案提供了另一种控制连接超时的方法(使用“fsockopen”而不是“curl”):http://stackoverflow.com/a/3690321/1869825 (2认同)
  • 你应该在curl中设置CURLOPT_CONNECTTIMEOUT和CURLOPT_TIMEOUT.请参见http://stackoverflow.com/a/27776164/1863432 (2认同)
  • 不是有效回复,问题是针对“file_get_contents”。反应很好,但不合适。 (2认同)

NVR*_*VRM 18

是的!通过在第三个参数中传递流上下文

这里超时为1s

file_get_contents("https://abcedef.com", 0, stream_context_create(["http"=>["timeout"=>1]]));
Run Code Online (Sandbox Code Playgroud)

来源https://www.php.net/manual/en/function.file-get-contents.php 的评论部分

HTTP 上下文选项

method
header
user_agent
content
request_fulluri
follow_location
max_redirects
protocol_version
timeout
Run Code Online (Sandbox Code Playgroud)

非 HTTP 流上下文

Socket
FTP
SSL
CURL
Phar
Context (notifications callback)
Zip
Run Code Online (Sandbox Code Playgroud)

  • `stream_context_create` 中给出的超时仅适用于连接超时。如果服务器在给定超时内回复(发送一些数据),但需要很长时间才能发送其剩余的有效负载,则此超时不会中断缓慢的传输。 (6认同)

Pas*_*get 6

值得注意的是,如果动态更改default_socket_timeout,在调用file_get_contents之后恢复其值可能很有用:

$default_socket_timeout = ini_get('default_socket_timeout');
....
ini_set('default_socket_timeout', 10);
file_get_contents($url);
...
ini_set('default_socket_timeout', $default_socket_timeout);
Run Code Online (Sandbox Code Playgroud)

  • @FlashThunder如果稍后需要先前超时的代码中还有另一个file_get_contents调用,则不会。在执行特定代码后立即恢复设置更改的代码,这通常是一种好习惯。 (2认同)
  • @FlashThunder,最好在调用后恢复 socket_timeout 值,以便后续调用同一函数**在同一脚本执行**中使用全局设置。 (2认同)