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_timeout
ini-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)
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)
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 的评论部分
method
header
user_agent
content
request_fulluri
follow_location
max_redirects
protocol_version
timeout
Run Code Online (Sandbox Code Playgroud)
Socket
FTP
SSL
CURL
Phar
Context (notifications callback)
Zip
Run Code Online (Sandbox Code Playgroud)
值得注意的是,如果动态更改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)
归档时间: |
|
查看次数: |
124592 次 |
最近记录: |