q666123 发表于 2017-4-5 11:40:08

PHP处理Socket连接超时问题的方法

当使用php函数 file_get_contents抓取远程网页时,如果连接超时将会输出一个Fatal Error,结果导致下面的代码不能运行,一般可采取两个解决方案:
1. 利用file_get_contents()第三个参数
<?php
$url = "http://172.16.0.40/die.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";
}
?>

2. 使用curl扩展库

<?php
$url = "http://172.16.0.40/die.php";
try {
echo date('Y-m-d h:i:s');
echo "<br/>";
//$buffer = file_get_contents($url);
$buffer = joy_file_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 joy_file_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;
}
?>
页: [1]
查看完整版本: PHP处理Socket连接超时问题的方法