PHP filesize MB/KB conversion
Here is a sample:
<?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;
}
?>
Format bytes to kilobytes, megabytes, gigabytes
function formatBytes($bytes, $precision = 2) {
$units = array('B', 'KB', 'MB', 'GB', 'TB');
$bytes = max($bytes, 0);
$pow = floor(($bytes ? log($bytes) : 0) / log(1024));
$pow = min($pow, count($units) - 1);
// Uncomment one of the following alternatives
// $bytes /= pow(1024, $pow);
// $bytes /= (1 << (10 * $pow));
return round($bytes, $precision) . ' ' . $units[$pow];
}
(Taken from php.net, there are many other examples there, but I like this one best :-)
PHP file size converter
You can round()
and following may help you. I use this code in production for a long time.
function convert_bytes_to_hr_format($size){
if (1024 > $size) {
return $size.' B';
} else if (1048576 > $size) {
return round( ($size / 1024) , 2). ' KB';
} else if (1073741824 > $size) {
return round( (($size / 1024) / 1024) , 2). ' MB';
} else if (1099511627776 > $size) {
return round( ((($size / 1024) / 1024) / 1024) , 2). ' GB';
}
}
How to Convert File size to only Megabytes using PHP
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;
?>
PHP convert KB MB GB TB etc to Bytes
Here's a function to achieve this:
function convertToBytes(string $from): ?int {
$units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
$number = substr($from, 0, -2);
$suffix = strtoupper(substr($from,-2));
//B or no suffix
if(is_numeric(substr($suffix, 0, 1))) {
return preg_replace('/[^\d]/', '', $from);
}
$exponent = array_flip($units)[$suffix] ?? null;
if($exponent === null) {
return null;
}
return $number * (1024 ** $exponent);
}
$testCases = ["13", "13B", "13KB", "10.5KB", "123Mi"];
var_dump(array_map('convertToBytes', $testCases));
Output:
array(5) { [0]=> int(13) [1]=> int(13) [2]=> int(13312) [3]=>
int(10752) [4]=> NULL } int(1)
human readable file size
Try something like this:
function humanFileSize($size,$unit="") {
if( (!$unit && $size >= 1<<30) || $unit == "GB")
return number_format($size/(1<<30),2)."GB";
if( (!$unit && $size >= 1<<20) || $unit == "MB")
return number_format($size/(1<<20),2)."MB";
if( (!$unit && $size >= 1<<10) || $unit == "KB")
return number_format($size/(1<<10),2)."KB";
return number_format($size)." bytes";
}
Correct way to convert size in bytes to KB, MB, GB in JavaScript
From this: (source)
Unminified and ES6'ed: (by the community)
function formatBytes(bytes, decimals = 2) {
if (!+bytes) return '0 Bytes'
const k = 1024
const dm = decimals < 0 ? 0 : decimals
const sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB']
const i = Math.floor(Math.log(bytes) / Math.log(k))
return `${parseFloat((bytes / Math.pow(k, i)).toFixed(dm))} ${sizes[i]}`
}
// Demo code
document.body.innerHTML += `<input type="text" oninput="document.querySelector('p').innerHTML=formatBytes(this.value)" value="1000"><p>1000 Bytes</p>`
filesize conversion bytes to kb/mb/gb function does not work as expected
When $bytes
is 0
the expression $bytes >= 1073741824 && $forceFormat === false
evaluates to false
. The switch
statement jumps to the first case
whose expression matches $bytes
. The following script demonstrates, that false
matches 0
.
<?php
switch (0) {
case false:
echo '0 is false';
break;
case true:
echo '0 is true';
break;
default:
echo '0 is something else';
break;
}
?>
Because you want to jump to the first case
which is true
you should use switch (true)
.
Related Topics
Passing JavaScript Variable to PHP Using Ajax
Laravel 5 Not Finding CSS Files
What Factors Make PHP Unicode-Incompatible
Rerouting All PHP Requests Through Index.Php
PHP Substr() Function with Utf-8 Leaves � Marks at the End
Can You Re-Populate File Inputs After Failed Form Submission with PHP or JavaScript
Simplest Way to Detect Client Locale in PHP
Wordpress Prepared Statement with In() Condition
Storing Arrays in the Database
Sqlstate[42S22]: Column Not Found: 1054 Unknown Column - Laravel
MySQL Error: 1364 Field 'Display_Name' Doesn't Have Default Value
How to Handle $_Post Data in MVC
How to Pull First 100 Characters of a String in PHP
Php: Read Specific Line from File
How to Kill A/All PHP Sessions
How to Prepare Statement for Update Query
Onbeforeprint() and Onafterprint() Equivalent for Non Ie Browsers