為什麼這篇Php fopen rb鄉民發文收入到精華區:因為在Php fopen rb這個討論話題中,有許多相關的文章在討論,這篇最有參考價值!作者johnney (戒不掉)看板PHP標題Re: [請益] fopen http timeout的...
※ 引述《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