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

php中curl、fsocket、file_get_content函数比较

程序员文章站 2022-05-16 18:18:35
...

最近做一个网页小偷程序的时候才发现file_get_content已经完全不能满足需求了。 我觉得,在读取远程内容时,file_get_content除了使用比curl便捷以外,其他都没有curl好

抓取远程内容,之前一直都在用file_get_content函数,其实早就知道有curl这么一个好东西的存在,但是看了一眼后感觉使用颇有些复杂,没有file_get_content那么简单,再就是需求也不大,所以没有学习使用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就好了。 基本语法:

  1. $my_curl = curl_init(); //初始化一个curl对象
  2. curl_setopt($my_curl, CURLOPT_URL, "http://bbs.it-home.org"); //设置你需要抓取的URL
  3. curl_setopt($my_curl,CURLOPT_RETURNTRANSFER,1); //设置是将结果保存到字符串中还是输出到屏幕上,1表示将结果保存到字符串
  4. $str = curl_exec($curl); //执行请求
  5. echo $str; //输出抓取的结果
  6. curl_close($curl); //关闭url请求
复制代码

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

  1. $config['context'] = stream_context_create(array('http' => array('method' => "GET",
  2. 'timeout' => 5//这个超时时间不稳定,经常不奏效
  3. )
  4. ));
复制代码

这时候,看一下服务器的连接池,会发现一堆类似的错误,让我头疼万分: file_get_contents(http://***): failed to open stream… 现在改用了curl库,写了一个函数替换:

  1. function curl_file_get_contents($durl){
  2. $ch = curl_init();
  3. curl_setopt($ch, CURLOPT_URL, $durl);
  4. curl_setopt($ch, CURLOPT_TIMEOUT, 5);
  5. curl_setopt($ch, CURLOPT_USERAGENT, _USERAGENT_);
  6. curl_setopt($ch, CURLOPT_REFERER,_REFERER_);
  7. curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
  8. $r = curl_exec($ch);
  9. curl_close($ch);
  10. return $r;
  11. }
复制代码

如此,除了真正的网络问题外,没再出现任何问题。 这是别人做过的关于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函数,不但稳定速度快,还能假冒浏览器欺骗目标地址哦!

说到curl与file_get_contents的用法,之前的文章中多有提及,这里推荐几篇不错的文章,大家做个参考:

  • PHP file_get_contents超时处理的设置方法
  • php file_get_contents抓取Gzip网页乱码的解决方法
  • php中file_get_contents超时问题的解决方法
  • PHP file_get_contents超时的设置方法
  • php file_get_content兼容性检测的例子
  • php file_get_contents抓取页面信息的代码
  • php file_get_contents函数抓取页面信息的代码

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

  1. $url='http://www.domain.com/';
  2. $html = file_get_contents($url);
  3. echo $html;
  4. ?>
复制代码

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

  1. $fp = fopen($url, 'r');
  2. stream_get_meta_data($fp);
  3. while(!feof($fp)) {
  4. $result .= fgets($fp, 1024);
  5. }
  6. echo "url body: $result";
  7. fclose($fp);
  8. ?>
复制代码

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

  1. $data = array ('foo' => 'bar');
  2. $data = http_build_query($data);
  3. $opts = array (
  4. 'http' => array (
  5. 'method' => 'POST',
  6. 'header'=> "Content-type: application/x-www-form-urlencodedrn" .
  7. "Content-Length: " . strlen($data) . "rn",
  8. 'content' => $data
  9. )
  10. );
  11. $context = stream_context_create($opts);
  12. $html = file_get_contents('http://localhost/e/admin/test.html', false, $context);
  13. echo $html;
  14. ?>
复制代码

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

  1. function get_url ($url,$cookie=false)
  2. {
  3. $url = parse_url($url);
  4. $query = $url[path]."?".$url[query];
  5. echo "Query:".$query;
  6. $fp = fsockopen( $url[host], $url[port]?$url[port]:80 , $errno, $errstr, 30);
  7. if (!$fp) {
  8. return false;
  9. } else {
  10. $request = "GET $query HTTP/1.1rn";
  11. $request .= "Host: $url[host]rn";
  12. $request .= "Connection: Closern";
  13. if($cookie) $request.="Cookie: $cookien";
  14. $request.="rn";
  15. fwrite($fp,$request);
  16. while()) {
  17. $result .= @fgets($fp, 1024);
  18. }
  19. fclose($fp);
  20. return $result;
  21. }
  22. }
  23. //获取url的html部分,去掉header
  24. function GetUrlHTML($url,$cookie=false)
  25. {
  26. $rowdata = get_url($url,$cookie);
  27. if($rowdata)
  28. {
  29. $body= stristr($rowdata,"rnrn");
  30. $body=substr($body,4,strlen($body));
  31. return $body;
  32. }
  33. return false;
  34. }
  35. ?>
复制代码

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

  1. function HTTP_Post($URL,$data,$cookie, $referrer="")
  2. {
  3. // parsing the given URL
  4. $URL_Info=parse_url($URL);
  5. // Building referrer
  6. if($referrer=="") // if not given use this script as referrer
  7. $referrer="111″;
  8. // making string from $data
  9. foreach($data as $key=>$value)
  10. $values[]="$key=".urlencode($value);
  11. $data_string=implode("&",$values);
  12. // Find out which port is needed – if not given use standard (=80)
  13. if(!isset($URL_Info["port"]))
  14. $URL_Info["port"]=80;
  15. // building POST-request:
  16. $request.="POST ".$URL_Info["path"]." HTTP/1.1n";
  17. $request.="Host: ".$URL_Info["host"]."n";
  18. $request.="Referer: $referern";
  19. $request.="Content-type: application/x-www-form-urlencodedn";
  20. $request.="Content-length: ".strlen($data_string)."n";
  21. $request.="Connection: closen";
  22. $request.="Cookie: $cookien";
  23. $request.="n";
  24. $request.=$data_string."n";
  25. $fp = fsockopen($URL_Info["host"],$URL_Info["port"]);
  26. fputs($fp, $request);
  27. while(!feof($fp)) {
  28. $result .= fgets($fp, 1024);
  29. }
  30. fclose($fp);
  31. return $result;
  32. }
  33. ?>
复制代码

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

  1. $ch = curl_init();
  2. $timeout = 5;
  3. curl_setopt ($ch, CURLOPT_URL, 'http://www.domain.com/');
  4. curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
  5. curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
  6. $file_contents = curl_exec($ch);
  7. curl_close($ch);
  8. echo $file_contents;
  9. ?>
复制代码

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了。 这和网络环境有关系。

就是这样了,以上通过实例介绍了php中url、fsocket、file_get_content函数在用法上的异同,希望对大家有所帮助。