Formatta byte in kilobyte, megabyte, gigabyte


184

Scenario: le dimensioni di vari file sono archiviate in un database come byte. Qual è il modo migliore per formattare queste informazioni su kilobyte, megabyte e gigabyte? Ad esempio ho un MP3 che Ubuntu visualizza come "5,2 MB (5445632 byte)". Come lo visualizzerei su una pagina Web come "5,2 MB" E i file con meno di un megabyte vengono visualizzati come KB e i file con un gigabyte e superiore vengono visualizzati come GB?


3
Credo che dovresti creare una funzione facendo questo. Dividi il numero per 1024 e guarda il risultato. Se è più di 1024, allora dividi di nuovo.
Ivan Nevostruev,

Risposte:


319
function formatBytes($bytes, $precision = 2) { 
    $units = array('B', 'KB', 'MB', 'GB', 'TB'); 

    $bytes = max($bytes, 0); 
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); 
    $pow = min($pow, count($units) - 1); 

    // Uncomment one of the following alternatives
    // $bytes /= pow(1024, $pow);
    // $bytes /= (1 << (10 * $pow)); 

    return round($bytes, $precision) . ' ' . $units[$pow]; 
} 

(Tratto da php.net , ci sono molti altri esempi lì, ma questo mi piace di più :-)


8
Se hai usato $bytes /= (1 << (10 * $pow))o simili, mi piacerebbe di più. :-P
Chris Jester-Young,

5
Ecco qua: D (personalmente, non mi piace l'aritmetica bit a bit, perché è difficile capire se non ci sei abituato ...)
Leo

3
@Justin è perché 9287695/1024/1024 è davvero 8.857 :)
Mahn

30
In realtà, è KiB, MiB, GiBe TiBdal momento che si sta dividendo per 1024. Se diviso per 1000questo sarebbe senza i.
Devator

8
Uncomment one of the following alternativesera qualcosa che non ho notato per 5 minuti ...
Arnis Juraga

211

Questa è l'implementazione di Chris Jester-Young, la più pulita che abbia mai visto, combinata con php.net e un argomento di precisione.

function formatBytes($size, $precision = 2)
{
    $base = log($size, 1024);
    $suffixes = array('', 'K', 'M', 'G', 'T');   

    return round(pow(1024, $base - floor($base)), $precision) .' '. $suffixes[floor($base)];
}

echo formatBytes(24962496);
// 23.81M

echo formatBytes(24962496, 0);
// 24M

echo formatBytes(24962496, 4);
// 23.8061M

8
ha 2 errori - aggiungi 1 alla dimensione (almeno piccola) dei file - non funziona con 0 (restituisce NAN)
maazza

Ben fatto. Esiste una versione al contrario?
Luca

3
un piccolo sogno : $suffixes = array('B', 'kB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'); voglio un disco rigido Yottabyte! :-P
SpYk3HH

1
ho dovuto lanciare la dimensione $ in un doppio per farlo funzionare. ecco cosa ha funzionato per me: funzione formatBytes ($ size, $ precision = 2) {$ base = log (floatval ($ size)) / log (1024); $ suffixes = array ('', 'k', 'M', 'G', 'T'); round di ritorno (pow (1024, $ base - piano ($ base)), $ precisione). $ suffissi [piano ($ base)]; }
Christopher Gray,

formatBytes(259748192, 3)ritorna 259748192 MBche non è giusto
Flip

97

pseudocodice:

$base = log($size) / log(1024);
$suffix = array("", "k", "M", "G", "T")[floor($base)];
return pow(1024, $base - floor($base)) . $suffix;

Microsoft e Apple usano 1024, dipende dal tuo caso d'uso.
Parsa Yazdani,

15

Questa è l' implementazione di Kohana , puoi usarla:

public static function bytes($bytes, $force_unit = NULL, $format = NULL, $si = TRUE)
{
    // Format string
    $format = ($format === NULL) ? '%01.2f %s' : (string) $format;

    // IEC prefixes (binary)
    if ($si == FALSE OR strpos($force_unit, 'i') !== FALSE)
    {
        $units = array('B', 'KiB', 'MiB', 'GiB', 'TiB', 'PiB');
        $mod   = 1024;
    }
    // SI prefixes (decimal)
    else
    {
        $units = array('B', 'kB', 'MB', 'GB', 'TB', 'PB');
        $mod   = 1000;
    }

    // Determine unit to use
    if (($power = array_search((string) $force_unit, $units)) === FALSE)
    {
        $power = ($bytes > 0) ? floor(log($bytes, $mod)) : 0;
    }

    return sprintf($format, $bytes / pow($mod, $power), $units[$power]);
}

La loro idea di avere un'opzione tra 1024 e 1000 di potenza è buona. Ma questa implementazione è davvero strana. $force_unite $sisembra fare la stessa cosa. Puoi anche passare qualsiasi stringa con una "i" al suo interno $force_unit, perché verificano la posizione. Anche la formattazione decimale è eccessiva.
Gus Neves,

14

Dividilo per 1024 per kb, 1024 ^ 2 per mb e 1024 ^ 3 per GB. Così semplice.


8

Solo la mia alternativa, breve e pulita:

/**
 * @param int $bytes Number of bytes (eg. 25907)
 * @param int $precision [optional] Number of digits after the decimal point (eg. 1)
 * @return string Value converted with unit (eg. 25.3KB)
 */
function formatBytes($bytes, $precision = 2) {
    $unit = ["B", "KB", "MB", "GB"];
    $exp = floor(log($bytes, 1024)) | 0;
    return round($bytes / (pow(1024, $exp)), $precision).$unit[$exp];
}

o, più stupido ed efficace:

function formatBytes($bytes, $precision = 2) {
    if ($bytes > pow(1024,3)) return round($bytes / pow(1024,3), $precision)."GB";
    else if ($bytes > pow(1024,2)) return round($bytes / pow(1024,2), $precision)."MB";
    else if ($bytes > 1024) return round($bytes / 1024, $precision)."KB";
    else return ($bytes)."B";
}

7

utilizzare questa funzione se si desidera un codice funzione

bcdiv ()

$size = 11485760;
echo bcdiv($size, 1048576, 0); // return: 10

echo bcdiv($size, 1048576, 2); // return: 10,9

echo bcdiv($size, 1048576, 2); // return: 10,95

echo bcdiv($size, 1048576, 3); // return: 10,953

6

So che forse è un po 'tardi per rispondere a questa domanda, ma più dati non uccideranno qualcuno. Ecco una funzione molto veloce:

function format_filesize($B, $D=2){
    $S = 'BkMGTPEZY';
    $F = floor((strlen($B) - 1) / 3);
    return sprintf("%.{$D}f", $B/pow(1024, $F)).' '.@$S[$F].'B';
}

EDIT: ho aggiornato il mio post per includere la correzione proposta da camomileCase:

function format_filesize($B, $D=2){
    $S = 'kMGTPEZY';
    $F = floor((strlen($B) - 1) / 3);
    return sprintf("%.{$D}f", $B/pow(1024, $F)).' '.@$S[$F-1].'B';
}

1
Ottieni una doppia B (BB) per piccoli valori di $ B, poiché una soluzione alternativa potrebbe fare "$ S = 'kMGTPEZY'" e invece di "@ $ S [$ F]" fai "@ $ S [$ F-1]".
camomilla

@camomileCase Due anni e mezzo dopo - ho aggiornato la mia risposta. Grazie.
David Bélanger,

4

Funzione semplice

function formatBytes($size, $precision = 0){
    $unit = ['Byte','KiB','MiB','GiB','TiB','PiB','EiB','ZiB','YiB'];

    for($i = 0; $size >= 1024 && $i < count($unit)-1; $i++){
        $size /= 1024;
    }

    return round($size, $precision).' '.$unit[$i];
}

echo formatBytes('1876144', 2);
//returns 1.79 MiB

3

Soluzione flessibile:

function size($size, array $options=null) {

    $o = [
        'binary' => false,
        'decimalPlaces' => 2,
        'decimalSeparator' => '.',
        'thausandsSeparator' => '',
        'maxThreshold' => false, // or thresholds key
        'suffix' => [
            'thresholds' => ['', 'K', 'M', 'G', 'T', 'P', 'E', 'Z', 'Y'],
            'decimal' => ' {threshold}B',
            'binary' => ' {threshold}iB',
            'bytes' => ' B'
        ]
    ];

    if ($options !== null)
        $o = array_replace_recursive($o, $options);

    $base = $o['binary'] ? 1024 : 1000;
    $exp = $size ? floor(log($size) / log($base)) : 0;

    if (($o['maxThreshold'] !== false) &&
        ($o['maxThreshold'] < $exp)
    )
        $exp = $o['maxThreshold'];

    return !$exp
        ? (round($size) . $o['suffix']['bytes'])
        : (
            number_format(
                $size / pow($base, $exp),
                $o['decimalPlaces'],
                $o['decimalSeparator'],
                $o['thausandsSeparator']
            ) .
            str_replace(
                '{threshold}',
                $o['suffix']['thresholds'][$exp],
                $o['suffix'][$o['binary'] ? 'binary' : 'decimal']
            )
        );
}

var_dump(size(disk_free_space('/')));
// string(8) "14.63 GB"
var_dump(size(disk_free_space('/'), ['binary' => true]));
// string(9) "13.63 GiB"
var_dump(size(disk_free_space('/'), ['maxThreshold' => 2]));
// string(11) "14631.90 MB"
var_dump(size(disk_free_space('/'), ['binary' => true, 'maxThreshold' => 2]));
// string(12) "13954.07 MiB"

2

Sono riuscito con la seguente funzione,

    function format_size($size) {
        $mod = 1024;
        $units = explode(' ','B KB MB GB TB PB');
        for ($i = 0; $size > $mod; $i++) {
            $size /= $mod;
        }
        return round($size, 2) . ' ' . $units[$i];
    }

2
Attenzione: K sta per Kelvin e k sta per chili.
ZeWaren,

2

Il mio approccio

    function file_format_size($bytes, $decimals = 2) {
  $unit_list = array('B', 'KB', 'MB', 'GB', 'PB');

  if ($bytes == 0) {
    return $bytes . ' ' . $unit_list[0];
  }

  $unit_count = count($unit_list);
  for ($i = $unit_count - 1; $i >= 0; $i--) {
    $power = $i * 10;
    if (($bytes >> $power) >= 1)
      return round($bytes / (1 << $power), $decimals) . ' ' . $unit_list[$i];
  }
}

2

Non so perché dovresti renderlo così complicato come gli altri.

Il codice seguente è molto più semplice da capire e circa il 25% più veloce rispetto alle altre soluzioni che utilizzano la funzione log (chiamata funzione 20 milioni di volte con parametri diversi)

function formatBytes($bytes, $precision = 2) {
    $units = ['Byte', 'Kilobyte', 'Megabyte', 'Gigabyte', 'Terabyte'];
    $i = 0;

    while($bytes > 1024) {
        $bytes /= 1024;
        $i++;
    }
    return round($bytes, $precision) . ' ' . $units[$i];
}

2

Ho fatto questo convertendo tutti gli input in byte e quindi convertendoli in qualsiasi output necessario. Inoltre, ho usato una funzione ausiliaria per ottenere la base 1000 o 1024, ma l'ho lasciata flessibile per decidere di usare 1024 sul tipo popolare (senza 'i', come MB invece di MiB).

    public function converte_binario($size=0,$format_in='B',$format_out='MB',$force_in_1024=false,$force_out_1024=false,$precisao=5,$return_format=true,$decimal=',',$centena=''){
    $out = false;

    if( (is_numeric($size)) && ($size>0)){
        $in_data = $this->converte_binario_aux($format_in,$force_in_1024);
        $out_data = $this->converte_binario_aux($format_out,$force_out_1024);

        // se formato de entrada e saída foram encontrados
        if( ((isset($in_data['sucesso'])) && ($in_data['sucesso']==true)) && ((isset($out_data['sucesso'])) && ($out_data['sucesso']==true))){
            // converte formato de entrada para bytes.
            $size_bytes_in = $size * (pow($in_data['base'], $in_data['pot']));
            $size_byte_out = (pow($out_data['base'], $out_data['pot']));
            // transforma bytes na unidade de destino
            $out = number_format($size_bytes_in / $size_byte_out,$precisao,$decimal,$centena);
            if($return_format){
                $out .= $format_out;
            }
        }
    }
    return $out;
}

public function converte_binario_aux($format=false,$force_1024=false){
    $out = [];
    $out['sucesso'] = false;
    $out['base'] = 0;
    $out['pot'] = 0;
    if((is_string($format) && (strlen($format)>0))){
        $format = trim(strtolower($format));
        $units_1000 = ['b','kb' ,'mb' ,'gb' ,'tb' ,'pb' ,'eb' ,'zb' ,'yb' ];
        $units_1024 = ['b','kib','mib','gib','tib','pib','eib','zib','yib'];
        $pot = array_search($format,$units_1000);
        if( (is_numeric($pot)) && ($pot>=0)){
            $out['pot'] = $pot;
            $out['base'] = 1000;
            $out['sucesso'] = true;
        }
        else{
            $pot = array_search($format,$units_1024);
            if( (is_numeric($pot)) && ($pot>=0)){
                $out['pot'] = $pot;
                $out['base'] = 1024;
                $out['sucesso'] = true;
            }
        }
        if($force_1024){
            $out['base'] = 1024;
        }
    }
    return $out;
}

1

prova questo ;)

function bytesToSize($bytes) {
                $sizes = ['Bytes', 'KB', 'MB', 'GB', 'TB'];
                if ($bytes == 0) return 'n/a';
                $i = intval(floor(log($bytes) / log(1024)));
                if ($i == 0) return $bytes . ' ' . $sizes[$i]; 
                return round(($bytes / pow(1024, $i)),1,PHP_ROUND_HALF_UP). ' ' . $sizes[$i];
            }
echo bytesToSize(10000050300);

1
function changeType($size, $type, $end){
    $arr = ['B', 'KB', 'MB', 'GB', 'TB'];
    $tSayi = array_search($type, $arr);
    $eSayi = array_search($end, $arr);
    $pow = $eSayi - $tSayi;
    return $size * pow(1024 * $pow) . ' ' . $end;
}

echo changeType(500, 'B', 'KB');

1
function convertToReadableSize($size)
{
  $base = log($size) / log(1024);
  $suffix = array("B", "KB", "MB", "GB", "TB");
  $f_base = floor($base);
  return round(pow(1024, $base - floor($base)), 1) . $suffix[$f_base];
}

Basta chiamare la funzione

echo convertToReadableSize(1024); // Outputs '1KB'
echo convertToReadableSize(1024 * 1024); // Outputs '1MB'

1

Questo lavoro con l'ultimo PHP

function formatBytes($bytes, $precision = 2) { 
    $units = array('B', 'KB', 'MB', 'GB', 'TB'); 

    $bytes = max($bytes, 0); 
    $pow = floor(($bytes ? log($bytes) : 0) / log(1024)); 
    $pow = min($pow, count($units) - 1); 

    $bytes /= pow(1024, $pow); 

    return round($bytes, $precision) . ' ' . $units[$pow]; 
} 

Tutto ciò che è stato fatto è la stessa copia esatta di un esempio da PHP.net che è stato fatto dal principale risponditore nel 2010 facendolo solo 8 anni dopo.
Jake Gould

1

Anche se un po 'stantio, questa libreria offre un'API di conversione testata e affidabile:

https://github.com/gabrielelana/byte-units

Una volta installato:

\ByteUnits\Binary::bytes(1024)->format();

// Output: "1.00KiB"

E per convertire nell'altra direzione:

\ByteUnits\Binary::parse('1KiB')->numberOfBytes();

// Output: "1024"

Oltre alla conversione di base, offre metodi per addizione, sottrazione, confronto, ecc.

Non sono affiliato a questa biblioteca.


0
function byte_format($size) {
    $bytes = array( ' KB', ' MB', ' GB', ' TB' );
    foreach ($bytes as $val) {
        if (1024 <= $size) {
            $size = $size / 1024;
            continue;
        }
        break;
    }
    return round( $size, 1 ) . $val;
}

0

Ecco un'implementazione semplificata della funzione format_size di Drupal :

/**
 * Generates a string representation for the given byte count.
 *
 * @param $size
 *   A size in bytes.
 *
 * @return
 *   A string representation of the size.
 */
function format_size($size) {
  if ($size < 1024) {
    return $size . ' B';
  }
  else {
    $size = $size / 1024;
    $units = ['KB', 'MB', 'GB', 'TB'];
    foreach ($units as $unit) {
      if (round($size, 2) >= 1024) {
        $size = $size / 1024;
      }
      else {
        break;
      }
    }
    return round($size, 2) . ' ' . $unit;
  }
}

0

È un po 'tardi, ma una versione leggermente più veloce della risposta accettata è di seguito:

function formatBytes($bytes, $precision)
{
    $unit_list = array
    (
        'B',
        'KB',
        'MB',
        'GB',
        'TB',
    );

    $bytes = max($bytes, 0);
    $index = floor(log($bytes, 2) / 10);
    $index = min($index, count($unit_list) - 1);
    $bytes /= pow(1024, $index);

    return round($bytes, $precision) . ' ' . $unit_list[$index];
}

È più efficiente, grazie all'esecuzione di una singola operazione log-2 invece di due operazioni log-e.

In realtà è più veloce fare la soluzione più ovvia di seguito, tuttavia:

function formatBytes($bytes, $precision)
{
    $unit_list = array
    (
        'B',
        'KB',
        'MB',
        'GB',
        'TB',
    );

    $index_max = count($unit_list) - 1;
    $bytes = max($bytes, 0);

    for ($index = 0; $bytes >= 1024 && $index < $index_max; $index++)
    {
        $bytes /= 1024;
    }

    return round($bytes, $precision) . ' ' . $unit_list[$index];
}

Questo perché l'indice viene calcolato contemporaneamente al valore del numero di byte nell'unità appropriata. Ciò ha ridotto i tempi di esecuzione di circa il 35% (un aumento della velocità del 55%).


0

Un'altra implementazione condensata che può tradurre in base 1024 (binaria) o base 1000 (decimale) e funziona anche con numeri incredibilmente grandi, quindi dell'uso della libreria bc:

function renderSize($byte,$precision=2,$mibi=true)
{
    $base = (string)($mibi?1024:1000);
    $labels = array('K','M','G','T','P','E','Z','Y');
    for($i=8;$i>=1;$i--)
        if(bccomp($byte,bcpow($base, $i))>=0)
            return bcdiv($byte,bcpow($base, $i), $precision).' '.$labels[$i-1].($mibi?'iB':'B');
    return $byte.' Byte';
}

Solo una piccola nota a margine; bcpow()genererà un'eccezione TypeError se $basee $inon sono valori stringa. Testato su PHP versione 7.0.11.
David Cery,

Grazie! Ho aggiunto l'incantatore di stringhe e risolto un errore di offset :)
Christian

0

Ho pensato di aggiungere un meshing di due mittenti (usando il codice di John Himmelman, che si trova in questa discussione, e usando il codice di Eugene Kuzmenko ) che sto usando.

function swissConverter($value, $format = true, $precision = 2) {
    //Below converts value into bytes depending on input (specify mb, for 
    //example)
    $bytes = preg_replace_callback('/^\s*(\d+)\s*(?:([kmgt]?)b?)?\s*$/i', 
    function ($m) {
        switch (strtolower($m[2])) {
          case 't': $m[1] *= 1024;
          case 'g': $m[1] *= 1024;
          case 'm': $m[1] *= 1024;
          case 'k': $m[1] *= 1024;
        }
        return $m[1];
        }, $value);
    if(is_numeric($bytes)) {
        if($format === true) {
            //Below converts bytes into proper formatting (human readable 
            //basically)
            $base = log($bytes, 1024);
            $suffixes = array('', 'KB', 'MB', 'GB', 'TB');   

            return round(pow(1024, $base - floor($base)), $precision) .' '. 
                     $suffixes[floor($base)];
        } else {
            return $bytes;
        }
    } else {
        return NULL; //Change to prefered response
    }
}

Questo utilizza il codice di Eugene per formattare i $valuebyte (mantengo i miei dati in MB, quindi converte i miei dati: 10485760 MBin 10995116277760) - quindi usa il codice di John per convertirlo nel valore di visualizzazione corretto ( 10995116277760in 10 TB).

L'ho trovato davvero utile, quindi ringrazio i due autori!


0

Funzione estremamente semplice per ottenere dimensioni di file umane.

Fonte originale: http://php.net/manual/de/function.filesize.php#106569

Copia / incolla codice:

<?php
function human_filesize($bytes, $decimals = 2) {
  $sz = 'BKMGTP';
  $factor = floor((strlen($bytes) - 1) / 3);
  return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}
?>

0

Ho sviluppato la mia funzione che converte le dimensioni della memoria leggibile dall'uomo in diverse dimensioni.

function convertMemorySize($strval, string $to_unit = 'b')
{
    $strval    = strtolower(str_replace(' ', '', $strval));
    $val       = floatval($strval);
    $to_unit   = strtolower(trim($to_unit))[0];
    $from_unit = str_replace($val, '', $strval);
    $from_unit = empty($from_unit) ? 'b' : trim($from_unit)[0];
    $units     = 'kmgtph';  // (k)ilobyte, (m)egabyte, (g)igabyte and so on...


    // Convert to bytes
    if ($from_unit !== 'b')
        $val *= 1024 ** (strpos($units, $from_unit) + 1);


    // Convert to unit
    if ($to_unit !== 'b')
        $val /= 1024 ** (strpos($units, $to_unit) + 1);


    return $val;
}


convertMemorySize('1024Kb', 'Mb');  // 1
convertMemorySize('1024', 'k')      // 1
convertMemorySize('5.2Mb', 'b')     // 5452595.2
convertMemorySize('10 kilobytes', 'bytes') // 10240
convertMemorySize(2048, 'k')        // By default convert from bytes, result is 2

Questa funzione accetta qualsiasi abbreviazione di dimensioni di memoria come "Megabyte, MB, Mb, mb, m, kilobyte, K, KB, b, Terabyte, T ....", quindi è un errore di battitura.


0

Basati sulla risposta di Leo , aggiungi

  • Supporto per negativo
  • Supporto 0 <valore <1 (Es .: 0.2, causerà log (valore) = numero negativo)

Se si desidera che l'unità massima sia Mega, passare a $units = explode(' ', ' K M');


function formatUnit($value, $precision = 2) {
    $units = explode(' ', ' K M G T P E Z Y');

    if ($value < 0) {
        return '-' . formatUnit(abs($value));
    }

    if ($value < 1) {
        return $value . $units[0];
    }

    $power = min(
        floor(log($value, 1024)),
        count($units) - 1
    );

    return round($value / pow(1024, $power), $precision) . $units[$power];
}
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.