How to show file size in MB

Discussion in 'PHP' started by Tuhin1234, Aug 4, 2017.

  1. #1
    $url     = 'http://example.com/files/opps.mp4';
    $headers = get_headers($url, true);
    
    if ( isset($headers['Content-Length']) ) {
       $size = 'file size:' . $headers['Content-Length'];
    }
    else {
       $size = 'file size: unknown';
    }
    
    echo $size;
    PHP:

    Result like "file size:4148758"
    this script show size as byte and how can i show in MB .
     
    Tuhin1234, Aug 4, 2017 IP
  2. intellect29

    intellect29 Member

    Messages:
    68
    Likes Received:
    2
    Best Answers:
    0
    Trophy Points:
    43
    #2
    
    <?php
    // Snippet from PHP Share: http://www.phpshare.org
    
    function formatSizeUnits($bytes){if($bytes >=1073741824){
    $bytes = number_format($bytes /1073741824,2).' GB';}
    elseif ($bytes >=1048576){
    $bytes = number_format($bytes /1048576,2).' MB';}
    elseif ($bytes >=1024){
    $bytes = number_format($bytes /1024,2).' KB';}
    elseif ($bytes >1){
    $bytes = $bytes .' bytes';}
    elseif ($bytes ==1){
    $bytes = $bytes .' byte';}else{
    $bytes ='0 bytes';}
    
    return $bytes;}?>
    
    PHP:
     
    intellect29, Aug 4, 2017 IP
  3. Tuhin1234

    Tuhin1234 Active Member

    Messages:
    178
    Likes Received:
    0
    Best Answers:
    0
    Trophy Points:
    71
    #3
    How can i use in my script
     
    Tuhin1234, Aug 4, 2017 IP
  4. deathshadow

    deathshadow Acclaimed Member

    Messages:
    9,732
    Likes Received:
    1,999
    Best Answers:
    253
    Trophy Points:
    515
    #4
    Try mine, it short circuits cleaner and avoids long compares:

    
    function formatSize($amount) {
    	if ($amount < 1024) return $amount . 'B';
    	$metricList = ['KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB'];
    	foreach ($metricList as $metric)
    		if (($amount /= 1024) < 1024)
    			return numberFormat($amount, 2) . $metric;
    	return number_format($amount, 2) . 'YB';
    } // formatSize
    
    Code (markup):
    Just add that function before whatever you're calling, then change just the one line:

       $size = 'file size:' . formatSize($headers['Content-Length']);
    Code (markup):
    ... to implement it. Mind you, Yettabytes might be a bit of overkill, but I'm a firm believer in being complete.
     
    deathshadow, Aug 8, 2017 IP