How to Convert Bytes to KB, MB, and More in PHP


When working with file sizes or data transfers, converting between units like bytes, kilobytes, and megabytes is a handy skill to have.

This tutorial walks you through creating a simple PHP function to handle these conversions easily.
Starting with a value in bytes, you’ll be able to convert it into bits, KB, MB, or whatever unit you need, making it perfect for applications like file uploads or data usage tracking.

PHP Code
  1. <?php
  2.  
  3. function convert_bytes($bytes, $to = "B") {
  4. // Ensure $bytes is a float for division
  5. $float = floatval($bytes);
  6.  
  7. switch ($to) {
  8. case "Kb": // Kilobits
  9. $float = ($float * 8) / 1024;
  10. break;
  11. case "b": // Bits
  12. $float *= 8;
  13. break;
  14. case "MB": // Megabytes
  15. $float /= (1024 * 1024);
  16. break;
  17. case "KB": // Kilobytes
  18. $float /= 1024;
  19. break;
  20. default: // Bytes
  21. break;
  22. }
  23.  
  24. // Format the result for better readability
  25. return number_format($float, 2);
  26. }
  27.  
  28. // Example usage
  29. $bytes = 1608200;
  30. $file_size_kb = convert_bytes($bytes, "KB");
  31. $file_size_mb = convert_bytes($bytes, "MB");
  32.  
  33. echo "File size: $file_size_kb KB";
  34. echo "File size: $file_size_mb MBn";
  35.  
  36. ?>


Sample Output:

File size: 1,570.51 KB
File size: 1.53 MB

chrism's Avatar
Author:
Views:
2,106
Rating:
Posted on Saturday 21st December 2024 at 07:51 PM
DanielXP
DanielXP's Avatar
Updated this tutorial to remove the need for a database, and given it a few samples