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

yipeiwu_com5年前PHP代码库
1、使用file_get_contents()
复制代码 代码如下:

<?php
$file = file_get_contents($url);
echo strlen($file);
?>

2. 使用get_headers()
复制代码 代码如下:

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

PS:
需要打开allow_url_fopen!
如未打开会显示
Warning: get_headers() [function.get-headers]: URL file-access is disabled in the server configuration
3.使用fsockopen()
复制代码 代码如下:

<?php
 function get_file_size($url) {
     $url = parse_url($url);

     if (empty($url['host'])) {
         return false;
     }

     $url['port'] = empty($url['post']) ? 80 : $url['post'];
     $url['path'] = empty($url['path']) ? '/' : $url['path'];

     $fp = fsockopen($url['host'], $url['port'], $error);

     if($fp) {
         fputs($fp, "GET " . $url['path'] . " HTTP/1.1\r\n");
         fputs($fp, "Host:" . $url['host']. "\r\n\r\n");

         while (!feof($fp)) {
             $str = fgets($fp);
             if (trim($str) == '') {
                 break;
             }elseif(preg_match('/Content-Length:(.*)/si', $str, $arr)) {
                 return trim($arr[1]);
             }
         }
         fclose ( $fp);
         return false;
     }else {
         return false;
     }
 }
 ?>

相关文章

thinkphp关于简单的权限判定方法

实例如下: <li> <label>权限</label> <cite> <input name="MB_right" type...

PHP判断图片格式的七种方法小结

PHP判断图片格式的七种方法小结

使用php判断文件图片的格式 复制代码 代码如下: <?php $imgurl = "//www.jb51.net/images/logo.gif"; //方法1 echo $ex...

php实现处理输入转义字符的代码

先来个函数,是最近WordPress 3.6中刚刚引入的 /** * Add slashes to a string or array of strings. * * This...

PHP return语句的另一个作用

一直以为,return只能出现在函数中,直到看了bbPress的代码: <?php require_once('./bb-load.php'); bb_reperm...

php闭包中使用use声明变量的作用域实例分析

本文实例讲述了php闭包中使用use声明变量的作用域。分享给大家供大家参考,具体如下: <?php function getClosure($i) { $i =...