Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Convert File size to only Megabytes using PHP

Tags:

html

php

I want to be able to take a file and only display it in megabytes. So for example, if I were to have a file that is only 120kb or 2mb, I want it to echo it out as 0.12mb and 2mb respectively.

Below is the code that I currently have and hoping if someone can help?

<?php
    function byte_convert($size) {
      # size smaller then 1kb
      if ($size < 1024) return $size . ' Byte';
      # size smaller then 1mb
      if ($size < 1048576) return sprintf("%4.2f KB", $size/1024);
      # size smaller then 1gb
      if ($size < 1073741824) return sprintf("%4.2f MB", $size/1048576);
      # size smaller then 1tb
      if ($size < 1099511627776) return sprintf("%4.2f GB", $size/1073741824);
      # size larger then 1tb
      else return sprintf("%4.2f TB", $size/1073741824);
    }


    $file_path = "pic1.jpg";

    $file_size = byte_convert(filesize($file_path));

    echo $file_size;

    ?>

Thank you.

like image 979
user3565031 Avatar asked Dec 21 '25 23:12

user3565031


1 Answers

just divide by 1024*1024

<?php
function get_mb($size) {
    return sprintf("%4.2f MB", $size/1048576);
}


$file_path = "pic1.jpg";

$file_size = get_mb(filesize($file_path));

echo $file_size;

?>
like image 117
Павел Иванов Avatar answered Dec 23 '25 14:12

Павел Иванов



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!