How to get remote file size from specific URL in PHP

1 Answer

0 votes
function get_file_size( $url ) {
    $curl = curl_init( $url );

    curl_setopt($curl, CURLOPT_NOBODY, true);
    curl_setopt($curl, CURLOPT_HEADER, true);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);

    $info = curl_exec($curl);
    curl_close($curl);

    if (preg_match("/^HTTP\/1\.[01] (\d\d\d)/", $info, $matches)) {
        $HTTP_status_code = (int)$matches[1];
    }

    if (preg_match("/Content-Length: (\d+)/", $info, $matches)) {
      $file_size = (int)$matches[1];
    }

    $result = -1;
    if ($HTTP_status_code == 200 || ($HTTP_status_code > 300 && $HTTP_status_code <= 308)) {
      $result = $file_size;
    }
    
    return $result;
}


$url = 'https://coupondiscountblog.com/images/xcg.jpg';

$file_size = get_file_size($url);

echo $file_size . " bytes";


  
/*
run:
          
1878 bytes

*/

 



answered Sep 21, 2019 by avibootz

Related questions

1 answer 266 views
3 answers 346 views
1 answer 175 views
2 answers 1,135 views
1 answer 227 views
3 answers 255 views
255 views asked Sep 21, 2019 by avibootz
...