分享七:文件处理

php读取本地文件常用函数(fopen与file_get_contents)

一:string file_get_contents ( string $filename [, bool $use_include_path = false [, resource $context [, int $offset = -1 [, int $maxlen ]]]] )

file_get_contents() 函数是用来将文件的内容读入到一个字符串中的首选方法。如果操作系统支持还会使用内存映射技术来增强性能。

注意:

一:超时问题:

解决办法:在超时返回错误后就象js中的settimeout那样进行一次尝试,错误超过3次或者5次后就确认为无法连线伺服器而彻底放弃。

1、增加超时的时间限制

修改file_get_contents延时可以用resource $context的timeout参数。(注意:set_time_limit只是设定你的PHP程式的超时时间,而不是file_get_contents函数读取URL的超时时间)

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

 

2:多次尝试

$cnt=0;
while($cnt < 3 && ($str=@file_get_contents('http...'))===FALSE){
   $cnt++;
}

 

二:读取大文件

解决办法:使用PHP的文件读取函数file_get_contents()进行分段读取

将在参数 offset 所指定的位置开始读取长度为 maxlen 的内容。如果失败,file_get_contents() 将返回 FALSE。

$str = $content=file_get_contents("2.sql",FALSE,NULL,1024*1024,1024);
echo $str;

 如果针对较小文件只是希望分段读取并以此读完可以使用fread()函数

$fp=fopen('2.sql','r');
while (!feof($fp)){
$str.=fread($fp, filesize ($filename)/10);//每次读出文件10分之1
//进行处理
}

echo $str;

 

三:解决file_get_contents无法请求https连接的方法

PHP.ini默认配置下,用file_get_contents读取https的链接,就会报如下错误

错误: Warning: fopen() [function.fopen]: Unable to find the wrapper "https" - did you forget to enable it when you configured PHP?

解决方案有3:

1.windows下的PHP,只需要到php.ini中把extension=php_openssl.dll前面的;删掉,重启服务就可以了。

2.linux下的PHP,就必须安装openssl模块,安装好了以后就可以访问了。

3.如果服务器你不能修改配置的话,那么就使用curl函数来替代file_get_contents函数,当然不是简单的替换啊。还有相应的参数配置才能正常使用curl函数。

对curl函数封装如下:

function http_request($url,$timeout=30,$header=array()){  
        if (!function_exists('curl_init')) {  
            throw new Exception('server not install curl');  
        }  
        $ch = curl_init();  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
        curl_setopt($ch, CURLOPT_HEADER, true);  
        curl_setopt($ch, CURLOPT_URL, $url);  
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);  
        if (!emptyempty($header)) {  
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);  
        }  
        $data = curl_exec($ch);  
        list($header, $data) = explode("\r\n\r\n", $data);  
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
        if ($http_code == 301 || $http_code == 302) {  
            $matches = array();  
            preg_match('/Location:(.*?)\n/', $header, $matches);  
            $url = trim(array_pop($matches));  
            curl_setopt($ch, CURLOPT_URL, $url);  
            curl_setopt($ch, CURLOPT_HEADER, false);  
            $data = curl_exec($ch);  
        }  

        if ($data == false) {  
            curl_close($ch);  
        }  
        @curl_close($ch);  
        return $data;  
}  

 

四:解析PHP中的file_get_contents获取远程页面乱码的问题

PHP的file_get_contents获取远程页面内容,如果是gzip编码过的,返回的字符串就是编码后的乱码
1、解决方法,找个ungzip的函数来转换下
2、给你的url加个前缀,这样调用
$content = file_get_contents("compress.zlib://".$url);
无论页面是否经过gzip压缩,上述代码都可以正常工作!

3:使用curl

function curl_get($url, $gzip=false){
        $curl = curl_init($url);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curl, CURLOPT_CONNECTTIMEOUT, 10);
        if($gzip) curl_setopt($curl, CURLOPT_ENCODING, "gzip"); // 关键在这里
        $content = curl_exec($curl);
        curl_close($curl);
        return $content;
}

 

五:利用file_get_contents("php://input", "r")获取原始表单内容

<form action="action.php" method="post" >
  <input type="text" name="userName"  id="userName" /><br/>
  <input type="text" name="userPass"  id="userPass" /><br/>
  <input type="submit" value="ok" />
 </form><form action="action.php" method="post" >
  <input type="text" name="userName"  id="userName" /><br/>
  <input type="text" name="userPass"  id="userPass" /><br/>
  <input type="submit" value="ok" />
 </form>


<?php
$raw_post_data = file_get_contents('php://input', 'r');
echo "-------\$_POST------------------<br/>";
echo var_dump($_POST) . "<br/>";
echo "-------php://input-------------<br/>";
echo $raw_post_data . "<br/>";
?>

 

 

其他:file_get_content实现Post

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.jb51.net', $data);

 

二:利用fopen

    //直接打开一个本地文件的实例代码  
    <?php  
    //假若我们本地的文件是一个名为xmlas.txt的文本  
    $filedemo = "xmlas.txt";  
    $fpdemo = fopen($filedemo,"r");  
    if ($fpdemo){  
     while(!feof($fpdemo)){  
      //1000读取的字符数  
      $datademo = fread($fpdemo, 1000);  
     }  
     fclose($fpdemo);  
    }  
    echo $datademo;  
    ?> 

 

三:PHP中fopen,file_get_contents,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模块扩展,功能很是强大。

5:file_get_contents设置超时有可能不奏效

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

 这时候,看一下服务器的连接池,会发现一堆类似的错误

file_get_contents(http://***): failed to open stream…

6:性能测试结果:

关于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

 

结论:

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

2:file_get_contents处理频繁小的时候,用它感觉挺好的。如果你的文件被1k+人处理。那么你的服务器cpu就等着高升吧。所以建议自己和大家在以后写php代码的时候使用curl库。

 


function http_request($url,$timeout=30,$header=array()){  
        if (!function_exists('curl_init')) {  
            throw new Exception('server not install curl');  
        }  
        $ch = curl_init();  
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
        curl_setopt($ch, CURLOPT_HEADER, true);  
        curl_setopt($ch, CURLOPT_URL, $url);  
        curl_setopt($ch, CURLOPT_TIMEOUT, $timeout);  
        if (!emptyempty($header)) {  
            curl_setopt($ch, CURLOPT_HTTPHEADER, $header);  
        }  
        $data = curl_exec($ch);  
        list($header, $data) = explode("\r\n\r\n", $data);  
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
        if ($http_code == 301 || $http_code == 302) {  
            $matches = array();  
            preg_match('/Location:(.*?)\n/', $header, $matches);  
            $url = trim(array_pop($matches));  
            curl_setopt($ch, CURLOPT_URL, $url);  
            curl_setopt($ch, CURLOPT_HEADER, false);  
            $data = curl_exec($ch);  
        }  

        if ($data == false) {  
            curl_close($ch);  
        }  
        @curl_close($ch);  
        return $data;  
}  

posted @ 2015-10-14 14:54  一束光  阅读(439)  评论(0编辑  收藏  举报

友情链接

CFC4N