2011-10-20

[PHP] 使用簡易單位顯示檔案大小

function ShowBytes($size) {
    $size=doubleval($size);
    $sizes = array(
        " Bytes", 
        " KB", 
        " MB", 
        " GB", 
        " TB"
    );
    if ($size == 0) { 
        return('n/a'); 
    } else {
        $i = floor( log($size, 1024) );
        return (round( $size/pow(1024, $i), 2) . $sizes[$i]); 
    }
}

/*demo*/
for($size=0; $size<3000000; $size+=512) {
    echo $size,' => ', ShowBytes($size),'<br />';
}
/*
0 => n/a
512 => 512 Bytes
1024 => 1 KB
1536 => 1.5 KB
2048 => 2 KB
2560 => 2.5 KB
3072 => 3 KB
3584 => 3.5 KB
*/

0 回應: