php file_get_contents() 用法

php 需要访问某个网页
<?php
$fh= file_get_contents('http://www.baidu.com/');
echo $fh;
?>

知识扩充

file_get_contents()模拟referer,cookie, 使用proxy等等

参考代码

ini_set('default_socket_timeout',120);
ini_set('user_agent','MSIE 6.0;');
$context=array('http' => array ('header'=> 'Referer: http://www.baidu.com/', ),);
$xcontext = stream_context_create($context);
echo $str=file_get_contents('http://www.webkaka.com/',FALSE,$xcontext);

首先解决file_get_contents的超时问题,在超时返回错误后就象js中的settimeout那样进行一次尝试,错误超过3次或者5次后就确认为无法连线伺服器而彻底放弃。
这裡就简单介绍两种解决方法:
一、增加超时的时间限制
注意:set_time_limit只是设定你的PHP程式的超时时间,而不是file_get_contents函数读取URL的超时时间。
我一开始以为set_time_limit也能影响到file_get_contents,后来经测试是无效的。真正的修改file_get_contents延时可以用resource $context的timeout参数:
PHP程序代码如下:
$opts = array(
'http'=>array(
'method'=>"GET",
'timeout'=>60,
)
);

$context = stream_context_create($opts);

$html =file_get_contents('http://www.jb51.net', false, $context);
fpassthru($fp);

二、多次尝试
PHP程序代码如下:
$cnt=0;
while($cnt < 3 && ($str=@file_get_contents('http...'))===FALSE){
$cnt++;
}

以上方法对付超时已经OK了。接下来演示一下用file_get_contents实现Post,如下:
PHP程序代码
function Post($url, $post = null){
$context = array();
if (is_array($post)) {
ksort($post);

  $context['http'] = array (
    'timeout'=>60,
    'method' => 'POST',
    'content' => http_build_query($post, '', '&'),
   );
}

return file_get_contents($url, false, stream_context_create($context));

}

$data = array (
'name' => 'test',
'email' => 'test@gmail.com',
'submit' => 'submit',
);

echo Post('http://www.www.com', $data);

注意文档头的Set_time_out否则整个文档都得超时了

file_get_contents("php://input")的使用方法
http://www.kuitao8.com/20140727/2867.shtml

文档部分转载http://www.jb51.net/article/55574.htm

转载于:https://www.cnblogs.com/webress/p/5509086.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值