Tools
- Sandbox
- Paste Code
- Snippets
- Generators
- Checks
- Convertors
- Home
- php
- Сonverters
- How to convert Bytes to Kb, Mb in PHP
How to convert Bytes to Kb, Mb in PHP
Snippet
Share
Do you find this snippet useful? Then share it with your friends or colleagues. This will help us to make our free web tools better.
Give function size in bytes and precision(2 by default):
<?php
function formatBytes($size, $precision = 2){
$base = log($size, 1024);
$suffixes = array('Bytes', 'Kb', 'Mb', 'Gb', 'Tb');
return round(pow(1024, $base - floor($base)), $precision) .' '. $suffixes[floor($base)];
}
// "1000 Bytes"
echo formatBytes(1000);
// "9.42 Mb"
echo formatBytes(9874321);