fopen(filename, mode)//打开一个文件或者url,mode以什么方式打开(r,r+,w,w+)

fwrite(handle, string)//返回写入的字符数,出现错误时则返回 FALSE 

fclose(handle)//关闭一个句柄

is_writable()//函数判断指定的文件是否可写

file_get_contents(filename)与curl的区别

1.fopen /file_get_contents 每次请求都会重新做DNS查询,并不对 DNS信息进行缓存。但是CURL会自动对DNS信息进行缓存。对同一域名下的网页或者图片的请求只需要一次DNS查询。这大大减少了DNS查询的次数。所以CURL的性能比fopen /file_get_contents 好很多。

2.fopen /file_get_contents 在请求HTTP时,使用的是http_fopen_wrapper,不会keeplive。而curl却可以。这样在多次请求多个链接时,curl效率会好一些。

3.fopen / file_get_contents 函数会受到php.ini文件中allow_url_open选项配置的影响。如果该配置关闭了,则该函数也就失效了。而curl不受该配置的影响。

4.curl 可以模拟多种请求,例如:POST数据,表单提交等,用户可以按照自己的需求来定制请求。而fopen / file_get_contents只能使用get方式获取数据。

file_get_contents 获取远程文件时会把结果都存在一个字符串中 fiels函数则会储存成数组形式 

因此,我还是比较倾向于使用curl来访问远程url。Php有curl模块扩展,功能很是强大。


下面是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性能对比PHP源代码如下:

通过淘宝ip获取地理位置

<?php 

function getCityCurl($ip) 

    $url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip; 

    $ch = curl_init(); 

    $timeout = 5; 

    curl_setopt ($ch, CURLOPT_URL, $url); 

    curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); 

    curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout); 

    $file_contents = curl_exec($ch); 

    curl_close($ch); 

  

    $ipinfo=json_decode($file_contents); 

    if($ipinfo->code=='1'){ 

        return false; 

    } 

    $city = $ipinfo->data->region.$ipinfo->data->city; 

    return $city; 

  

function getCity($ip) 

    $url="http://ip.taobao.com/service/getIpInfo.php?ip=".$ip; 

    $ipinfo=json_decode(file_get_contents($url)); 

    if($ipinfo->code=='1'){ 

        return false; 

    } 

    $city = $ipinfo->data->region.$ipinfo->data->city; 

    return $city; 

  

// for file_get_contents 

$startTime=explode(' ',microtime()); 

$startTime=$startTime[0] + $startTime[1]; 

for($i=1;$i<=10;$i++) 

   echo getCity("121.207.247.202")."</br>"; 

$endTime = explode(' ',microtime()); 

$endTime = $endTime[0] + $endTime[1]; 

$totalTime = $endTime - $startTime; 

echo 'file_get_contents:'.number_format($totalTime, 10, '.', "")." seconds</br>"; 

  

//for curl 

$startTime2=explode(' ',microtime()); 

$startTime2=$startTime2[0] + $startTime2[1]; 

for($i=1;$i<=10;$i++) 

   echo getCityCurl('121.207.247.202')."</br>"; 

$endTime2 = explode(' ',microtime()); 

$endTime2=$endTime2[0] + $endTime2[1]; 

$totalTime2 = $endTime2 - $startTime2; 

echo "curl:".number_format($totalTime2, 10, '.', "")." seconds"; 

?>