欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

php中curl、fsocket、file_get_content三个函数的使用比较

程序员文章站 2022-07-22 08:22:37
抓取远程内容,之前一直都在用file_get_content函数,其实早就知道有curl这么一个好东西的存在,但是看了一眼后感觉使用颇有些复杂,没有file_get_con...

抓取远程内容,之前一直都在用file_get_content函数,其实早就知道有curl这么一个好东西的存在,但是看了一眼后感觉使用颇有些复杂,没有file_get_content那么简单,再就是需求也不大,所以没有学习使用curl。
直到最近,要做一个网页小偷程序的时候才发现file_get_content已经完全不能满足需求了。我觉得,在读取远程内容的时候,file_get_content除了使用比curl便捷以外,其他都没有curl好。

php中curl和file_get_content的一些比较

主要区别:

学习才发现,curl支持很多协议,有ftp, ftps, http, https, gopher, telnet, dict, file以及ldap,也就是说,它能做到很多file_get_content做不到的事情。curl在php可以实现远程获取和采集内容;实现php网页版的ftp上传下载;实现模拟登陆;实现接口对接(api),数据传输;实现模拟cookie;下载文件断点续传等等,功能十分强大。

了解curl一些基本的使用后,才发现其实并不难,只不过记住里面一些设置参数,难弄一点,但是我们记住几个常用的就可以了。

开启curl:

因为php默认是不支持curl功能的,因此如果要用curl的话,首先需要在php.ini中开启该功能,即去掉 ;extension= php_curl.dll 前面的分号,然后保存后重启apache/iis就好了。

基本语法:

复制代码 代码如下:

$my_curl = curl_init();    //初始化一个curl对象
curl_setopt($my_curl, curlopt_url, "//www.jb51.net");    //设置你需要抓取的url
curl_setopt($my_curl,curlopt_returntransfer,1);    //设置是将结果保存到字符串中还是输出到屏幕上,1表示将结果保存到字符串
$str = curl_exec($curl);    //执行请求
echo $str;    //输出抓取的结果
curl_close($curl);    //关闭url请求

最近需要获取别人网站上的音乐数据。用了file_get_contents函数,但是总是会遇到获取失败的问题,尽管按照手册中的例子设置了超时,可多数时候不会奏效:

$config['context'] = stream_context_create(array('http' => array('method' => "get",
'timeout' => 5//这个超时时间不稳定,经常不奏效
)
));

这时候,看一下服务器的连接池,会发现一堆类似的错误,让我头疼万分:
file_get_contents(http://***): failed to open stream…

现在改用了curl库,写了一个函数替换:
function curl_file_get_contents($durl){
$ch = curl_init();
curl_setopt($ch, curlopt_url, $durl);
curl_setopt($ch, curlopt_timeout, 5);
curl_setopt($ch, curlopt_useragent, _useragent_);
curl_setopt($ch, curlopt_referer,_referer_);
curl_setopt($ch, curlopt_returntransfer, 1);
$r = curl_exec($ch);
curl_close($ch);
return $r;
}

如此,除了真正的网络问题外,没再出现任何问题。
这是别人做过的关于curl和file_get_contents的测试:
file_get_contents抓取google.com需用秒数:

2.31319094
2.30374217
2.21512604
3.30553889
2.30124092

curl使用的时间:

0.68719101
0.64675593
0.64326
0.81983113
0.63956594

差距很大?呵呵,从我使用的经验来说,这两个工具不只是速度有差异,稳定性也相差很大。

建议对网络数据抓取稳定性要求比较高的朋友使用上面的 curl_file_get_contents函数,不但稳定速度快,还能假冒浏览器欺骗目标地址哦!

方法1: 用file_get_contents 以get方式获取内容

复制代码 代码如下:

<?php
$url='http://www.domain.com/';
$html = file_get_contents($url);
echo $html;
?>

方法2: 用fopen打开url, 以get方式获取内容

复制代码 代码如下:

<?php
$fp = fopen($url, 'r');
stream_get_meta_data($fp);
while(!feof($fp)) {
$result .= fgets($fp, 1024);
}
echo "url body: $result";
fclose($fp);
?>

方法3:用file_get_contents函数,以post方式获取url

复制代码 代码如下:

<?php
$data = array ('foo' => 'bar');
$data = http_build_query($data);

$opts = array (
'http' => array (
'method' => 'post',
'header'=> "content-type: application/x-www-form-urlencodedrn" .
"content-length: " . strlen($data) . "rn",
'content' => $data
)
);
$context = stream_context_create($opts);
$html = file_get_contents('http://localhost/e/admin/test.html', false, $context);
echo $html;
?>

方法4:用fsockopen函数打开url,以get方式获取完整的数据,包括header和body

复制代码 代码如下:

<?php
function get_url ($url,$cookie=false)
{
$url = parse_url($url);
$query = $url[path]."?".$url[query];
echo "query:".$query;
$fp = fsockopen( $url[host], $url[port]?$url[port]:80 , $errno, $errstr, 30);
if (!$fp) {
return false;
} else {
$request = "get $query http/1.1rn";
$request .= "host: $url[host]rn";
$request .= "connection: closern";
if($cookie) $request.="cookie: $cookien";
$request.="rn";
fwrite($fp,$request);
while()) {
$result .= @fgets($fp, 1024);
}
fclose($fp);
return $result;
}
}
//获取url的html部分,去掉header
function geturlhtml($url,$cookie=false)
{
$rowdata = get_url($url,$cookie);
if($rowdata)
{
$body= stristr($rowdata,"rnrn");
$body=substr($body,4,strlen($body));
return $body;
}
return false;
}
?>

方法5:用fsockopen函数打开url,以post方式获取完整的数据,包括header和body

复制代码 代码如下:

<?php
function http_post($url,$data,$cookie, $referrer="")
{
// parsing the given url
$url_info=parse_url($url);

// building referrer
if($referrer=="") // if not given use this script as referrer
$referrer="111″;

// making string from $data
foreach($data as $key=>$value)
$values[]="$key=".urlencode($value);
$data_string=implode("&",$values);

// find out which port is needed – if not given use standard (=80)
if(!isset($url_info["port"]))
$url_info["port"]=80;

// building post-request:
$request.="post ".$url_info["path"]." http/1.1n";
$request.="host: ".$url_info["host"]."n";
$request.="referer: $referern";
$request.="content-type: application/x-www-form-urlencodedn";
$request.="content-length: ".strlen($data_string)."n";
$request.="connection: closen";

$request.="cookie: $cookien";

$request.="n";
$request.=$data_string."n";

$fp = fsockopen($url_info["host"],$url_info["port"]);
fputs($fp, $request);
while(!feof($fp)) {
$result .= fgets($fp, 1024);
}
fclose($fp);

return $result;
}
?>

方法6:使用curl库,使用curl库之前,可能需要查看一下php.ini是否已经打开了curl扩展

复制代码 代码如下:

<?php
$ch = curl_init();
$timeout = 5;
curl_setopt ($ch, curlopt_url, 'http://www.domain.com/');
curl_setopt ($ch, curlopt_returntransfer, 1);
curl_setopt ($ch, curlopt_connecttimeout, $timeout);
$file_contents = curl_exec($ch);
curl_close($ch);
echo $file_contents;
?>

php中 curl, fsockopen ,file_get_contents 三个函数 都可以实现采集模拟发言 。三者有什么区别,或者讲究么

赵永斌:
有些时候用file_get_contents()调用外部文件,容易超时报错。换成curl后就可以.具体原因不清楚
curl 效率比file_get_contents()和fsockopen()高一些,原因是curl会自动对dns信息进行缓存(亮点啊有我待亲测)

范佳鹏:
file_get_contents curl fsockopen
在当前所请求环境下选择性操作,没有一概而论:
具我们公司开发kbi应用来看:
刚开始采用:file_get_contents
后来采用:fsockopen
最后到至今采用:curl

(远程)我个人理解到的表述如下(不对请指出,不到位请补充)
file_get_contents 需要php.ini里开启allow_url_fopen,请求http时,使用的是http_fopen_wrapper,不会keeplive.curl是可以的。
file_get_contents()单个执行效率高,返回没有头的信息。
这个是读取一般文件的时候并没有什么问题,但是在读取远程问题的时候就会出现问题。
如果是要打一个持续连接,多次请求多个页面。那么file_get_contents和fopen就会出问题。
取得的内容也可能会不对。所以做一些类似采集工作的时候,肯定就有问题了。
sock较底层,配置麻烦,不易操作。 返回完整信息。

潘少宁-腾讯:
file_get_contents 虽然可以获得某url的内容,但不能post get啊。
curl 则可以post和get啊。还可以获得head信息
而socket则更底层。可以设置基于udp或是tcp协议去交互
file_get_contents 和 curl 能干的,socket都能干。
socket能干的,curl 就不一定能干了
file_get_contents 更多的时候 只是去拉取数据。效率比较高 也比较简单。
赵的情况这个我也遇到过,我通过curl设置host 就ok了。 这和网络环境有关系