file_get_contents 超时问题与基础语法
天气转晴,但技术难题随之而来。在实现两个站点间用户数据同步的过程中,若使用 PHP 函数 file_get_contents 抓取并执行远程页面,一旦遭遇连接超时,不仅会抛出 Fatal Error,还可能导致程序运行极慢,进而阻塞后续代码的执行。首先需要了解 PHP file_get_contents() 函数的基本特性。
定义和用法
file_get_contents() 函数的主要功能是将整个文件读取到一个字符串变量中。
该函数与 file() 类似,区别在于 file() 返回数组,而 file_get_contents() 直接返回字符串。
作为将文件内容读入字符串的首选方法,file_get_contents() 在操作系统支持的情况下,还会利用内存映射技术来提升性能表现。
语法
file_get_contents(path, include_path, context, start, max_length)。各参数及其描述如下:
path:必需参数,指定需要读取的文件路径。
include_path:可选参数。若希望在 include_path 目录中也搜寻文件,可将此参数设为 "1"。
context:可选参数,用于规定文件句柄的环境配置。
context 是一套可修改流行为的选项集合。若传入 null,则忽略该参数。
start:可选参数,指定从文件中开始读取的位置。此参数为 PHP 5.1 新增。
max_length:可选参数,规定读取的最大字节数。此参数同样为 PHP 5.1 新增。
说明
对 context 的支持是在 PHP 5.0.0 版本中添加的。
针对超时或页面响应过慢的问题,通常可以采取以下两种解决方案:
一. 利用file_get_contents()第三个参数
$url = "http://zhoz.com/zhoz.php";
$ctx = stream_context_create(array('http' => array('timeout' => 10)
)
);
$result = @file_get_contents($url, 0, $ctx);
if($result){
var_dump($result);
}else{
echo " Buffer is empty";
}
?>经测试,方法一在本地环境表现良好,但在外网测试场景下(例如从中国服务器连接至美国服务器)极易出现超时情况。
由于 TimeOut 设置在实际跨地域测试中往往失效,建议采用以下方式:
二. 使用curl扩展库
$url = "http://zhoz.com/zhoz.php";try {
echo date('Y-m-d h:i:s');
echo "";
//$buffer = file_get_contents($url);
$buffer = zhoz_get_contents($url);
echo date('Y-m-d h:i:s');
if(empty($buffer)) {
echo " Buffer is empty";
} else {
echo " Buffer is not empty";
}
} catch(Exception $e) {
echo "error ";
}
function zhoz_get_contents($url, $second = 5) {
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_HEADER,0);
curl_setopt($ch,CURLOPT_TIMEOUT,$second);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
?>综上所述,应根据具体的系统环境选择最合适的调用方法:
function vita_get_url_content($url) {
if(function_exists('file_get_contents')) {
$file_contents = file_get_contents($url);
} else {
$ch = curl_init();
$timeout = 5;curl_setopt ($ch, CURLOPT_URL, $url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
}
return $file_contents;
}
?>