---
title: "curl, fsockopen ,file_get_contents 几个方法的效率对比"
author: "yd514"
date: "2013-09-09T13:56:03Z"
tags: []
categories: ["Web前端"]
slug: "curl-fsockopen-file-get-contents"
draft: false
lastmod: "2013-09-09T13:56:03Z"
id: 1856793
url: "https://yd514.iteye.com/blog/1856793"
---

## php读取网络文件 curl, fsockopen ,file\_get\_contents 几个方法的效率对比

[curl效率及稳定原来可以远远超越file\_get\_contents](http://u.ajzhan.com/post/13/)

 

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

$config\['context'] = stream\_context\_create(array(‘http’ =&gt; array(‘method’ =&gt; “GET”,   
   ’timeout’ =&gt; 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函数，不但稳定速度快，还能假冒浏览器欺骗目标地址哦！

 

 

 

看到的其他文章收藏于此===============================

php fsockopen

方法1: 用file\_get\_contents 以get方式获取内容  
&lt;?php  
$url='http://www.domain.com/';  
$html = file\_get\_contents($url);  
echo $html;  
?&gt;

方法2: 用fopen打开url, 以get方式获取内容  
&lt;?php  
$fp = fopen($url, 'r');  
stream\_get\_meta\_data($fp);  
while(!feof($fp)) {  
$result .= fgets($fp, 1024);  
}  
echo "url body: $result";  
fclose($fp);  
?&gt;

 

 

方法3：用file\_get\_contents函数,以post方式获取url  
&lt;?php  
$data = array ('foo' =&gt; 'bar');  
$data = http\_build\_query($data);

$opts = array (  
'http' =&gt; array (  
'method' =&gt; 'POST',  
'header'=&gt; "Content-type: application/x-www-form-urlencoded\\r\\n" .  
"Content-Length: " . strlen($data) . "\\r\\n",  
'content' =&gt; $data  
)  
);

$context = stream\_context\_create($opts);  
$html = file\_get\_contents('http://localhost/e/admin/test.html', false, $context);

echo $html;  
?&gt;

 

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

&lt;?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.1\\r\\n";  
$request .= "Host: $url\[host]\\r\\n";  
$request .= "Connection: Close\\r\\n";  
if($cookie) $request.="Cookie:   $cookie\\n";  
$request.="\\r\\n";  
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,"\\r\\n\\r\\n");  
$body=substr($body,4,strlen($body));  
return $body;  
}

    return false;  
}  
?&gt;

 

 

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

&lt;?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=&gt;$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.1\\n";  
$request.="Host: ".$URL\_Info\["host"]."\\n";  
$request.="Referer: $referer\\n";  
$request.="Content-type: application/x-www-form-urlencoded\\n";  
$request.="Content-length: ".strlen($data\_string)."\\n";  
$request.="Connection: close\\n";

    $request.="Cookie:   $cookie\\n";

    $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;  
}

?&gt;

 

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

&lt;?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;  
?&gt;