PHP three solutions for getting remote file sizes

  • 2020-07-21 07:19:48
  • OfStack

1. Use file_get_contents()

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

2. Use the get_headers ()

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

PS:
You need to open allow_url_fopen!
If not, it will be displayed
Warning: get_headers() [function.get-headers]: URL file-access is disabled in the server configuration
3. Use the 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;
     }
 }
 ?>

Related articles: