> uploadtext_

v1.0.0 - Secure text sharing node

File size formatter

Owner: coffeeman Created: 2026-05-01 22:44:43 Size: 0.86 KB Expires: Never
[ RAW ] [ NEW ]
tty1
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
<?php
/**
 * Converts raw bytes into a human-readable format.
 * Perfect for showing users the size of their text uploads.
 *
 * @param int $bytes The number of bytes
 * @param int $precision Number of decimal places
 * @return string
 */
function formatBytes(int $bytes, int $precision = 2): string 
{
    if ($bytes <= 0) {
        return '0 B';
    }

    $units = ['B', 'KB', 'MB', 'GB', 'TB', 'PB'];
    
    // Determine the magnitude of the size
    $pow = floor(log($bytes) / log(1024));
    $pow = min($pow, count($units) - 1); // Prevent out of bounds
    
    // Calculate the value using bitwise shifts for performance
    $value = $bytes / (1 << (10 * $pow)); 
    
    return round($value, $precision) . ' ' . $units[$pow];
}

// Usage Example:
// echo formatBytes(1048576); // Outputs: 1 MB
// echo formatBytes(1500);    // Outputs: 1.46 KB