作者johnney (戒不掉)
看板PHP
标题Re: [请益] fopen http timeout的问题
时间Wed Dec 13 18:40:47 2006
※ 引述《breazer ()》之铭言:
: 程式里面有一行code 是长这个样子
: $fp1 = fopen("http://192.168.0.141/xxx","r");
: 可是如果192.168.0.141 这个ip的电脑网路线被拔掉之後
: 会让这一行code卡住 直到php本身timeout
: 结果就只执行到这一行code就停了 之後都跑不到
: 我该怎麽限制这行code的执行时间??
: 好让这行执行太久的时候 可以跳过这行继续执行下去
借花献佛...
http://tw.php.net/manual/en/function.fopen.php
Ex1.
If you need fopen() on a URL to timeout, you can do like:
<?php
$timeout = 3;
$old = ini_set('default_socket_timeout', $timeout);
$file = fopen('
http://example.com', 'r');
ini_set('default_socket_timeout', $old);
stream_set_timeout($file, $timeout);
stream_set_blocking($file, 0);
//the rest is standard
?>
Ex2.
During development of a set of non-blocking functions for downloading files
from http-servers I've discovered that it's not possible to set timeout
for fopen('
http://somesite.com/somefile', 'rb').
All functions for controlling non-blocking mode (stream_set_blocking,
stream_set_timeout, stream_context_set_option) use resource handle
that is created via fopen(). But fopen() for HTTP connections
internally makes quite a big set of actions: it creates socket,
resolves webserver name, establishes actual connection.
So hanging can occur anywhere in resolving and creating tcp-connection
but you cannot control it.
Solutions:
1) Use socket functions. Set socket in non-blocking mode just after creation.
Implement HTTP-protocol yourself. In source code use these manually
created functions.
2) Write a wrapper for myprotocol://, which internally will use first solution,
but in source code you'll use
fopen('myprotocol://somesite.com/somefile', 'rb') with some way
to set timeout before calling it.
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 140.119.190.160
1F:推 breazer:我试了第一个方法是可以work的 感谢!!! 12/13 19:19