Products
GG网络技术分享 2025-11-14 02:43 2
根据给的代码片段和说说 您遇到的问题是用 file_get_contents 获取远程页面时兴许由于超时而没有返回 false。
file_get_contents 超时问题

file_get_contents 函数默认不返回 false 在超时的情况下除非显式设置 timeout 参数。file_get_contents 超时 它将返回空字符串,而不是 false。代码片段中的问题
@fsockopen,这会抑制错误信息。显式设置 timeout
file_get_contents 在超时后返回 false,Neng在函数调用时设置 timeout 参数。
php
$context = stream_context_create(array(
'http' => array(
'timeout' => 30 // 设置超时时候为30秒
)
));
$content = file_get_contents;
if {
// 处理超时情况
}
处理 fsockopen 超时
fsockopen,Neng通过 stream_set_timeout 来设置超时时候。
php
$fp = fsockopen;
if {
// 处理错误
}
stream_set_timeout;
优化代码
stream_set_blocking 来关闭阻塞模式,这兴许会搞优良效率。错误处理
feof 来检查是不是Yi经读取到文件末尾。代码示例 php $url = "http://www.vketch.com/"; $timeout = 30; // 设置超时时候为30秒 $fp = fsockopen; if { die "); }
$out = "GET $url HTTP/1.1\r "; $out .= "Host: $url\r "; $out .= "Connection: Close\r \r ";
fwrite; streamsetblocking; streamsettimeout; $content = ""; while ) { $content .= fread; }
fclose;
if { die; }
echo $content;
通过以上步骤, 您得Neng够geng优良地处理超时问题,并在 PHP 中平安地获取远程页面内容。
Demand feedback