size_format()
Converts bytes to a human-readable format: 500 B, 63 KB, 9 MB, 2 GB, 1 TB.
Formats file size into a readable format.
All file sizes in PHP are stored in bytes and obtained in them using filesize() or some other way. But it is much easier to read 1 KB than 1024 B.
The function takes the number of bytes and converts them to the amount of:
- kilobytes (KB)
- megabytes (MB)
- gigabytes (GB)
- terabytes (TB)
- petabytes (PB)
- exabytes (EB)
- zettabytes (ZB)
- yottabytes (YB)
Also, it is important to remember that the maximum integer on 32-bit systems is limited to 2147483647, while on a 64-bit system it is 9223372036854775807. Therefore, when you need to specify a number greater than the system can handle, specify the number as a string.
wp_convert_hr_to_bytes() — a similar function that, conversely, converts a shortened byte value to an integer byte value. For example, 1Mb is converted to 1048576.
Use this custom function to convert a large integer into a readable form 1500 >> 1.5 тыс..
No Hooks.
Returns
String|false. A string or false if conversion failed.
Usage
size_format( $bytes, $decimals );
- $bytes(int/string) (required)
- The number of bytes to convert. Keep in mind that PHP has a maximum allowable size for integers, and it is small on 32-bit systems.
- $decimals(int)
- The number of digits after the decimal point.
Default: 0
Examples
#1 Byte conversion demonstration
echo size_format( 99 ); //> 99 B echo size_format( 9999 ); //> 10 KB echo size_format( '9999' ); //> 10 KB echo size_format( 9999, 2 ); //> 9,76 KB echo size_format( 9999999 ); //> 10 MB echo size_format( 9999999999 ); //> 9 GB echo size_format( 9999999999999 ); //> 9 TB
#2 Display the size of a file in human-readable format
$file_size = 1229; // filesize in bytes echo size_format( $file_size, $decimals = 2 ); // 1.20 KB
Changelog
| Since 2.3.0 | Introduced. |
| Since 6.0.0 | Support for PB, EB, ZB, and YB was added. |