PHP 获取远程文件的大小的3种方法

1、使用file_get_contents()

1 <?php
2 $file = file_get_contents($url);
3 echo strlen($file);
4 ?>

2. 使用get_headers()

1 <?php
2 $header_array = get_headers($url, true);
3 $size = $header_array['Content-Length'];
4 echo $size;
5 ?>

PS:

需要打开allow_url_fopen!
如未打开会显示
Warning: get_headers() [function.get-headers]: URL file-access is disabled in the server configuration

3.使用fsockopen()

 1 <?php
 2 function get_file_size($url) {
 3     $url = parse_url($url);
 4  
 5     if (empty($url['host'])) {
 6         return false;
 7     }
 8  
 9     $url['port'] = empty($url['post']) ? 80 : $url['post'];
10     $url['path'] = empty($url['path']) ? '/' : $url['path'];
11  
12     $fp = fsockopen($url['host'], $url['port'], $error);
13  
14     if($fp) {
15         fputs($fp, "GET " . $url['path'] . " HTTP/1.1\r\n");
16         fputs($fp, "Host:" . $url['host']. "\r\n\r\n");
17  
18         while (!feof($fp)) {
19             $str = fgets($fp);
20             if (trim($str) == '') {
21                 break;
22             }elseif(preg_match('/Content-Length:(.*)/si', $str, $arr)) {
23                 return trim($arr[1]);
24             }
25         }
26         fclose ( $fp);
27         return false;
28     }else {
29         return false;
30     }
31 }
32  
33 ?>

 

posted @ 2013-07-05 11:37  Rayol  阅读(406)  评论(1编辑  收藏  举报