Calculate and convert byte file size to kB, MB, GB, etc

Asked

Viewed 3,237 times

0

Hello would like to know how I can complement the code below so that the filesize via remote URL returns the result of the file size on MB because the current code is returning the result of the file size in bytes.

function remotefileSize($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
    curl_exec($ch);
    $filesize = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
    curl_close($ch);
    if ($filesize) return $filesize;
}


echo remotefileSize('http://thumb.mais.uol.com.br/15233302-medium.jpg');

4 answers

1

The base calculation is 1024 because 1kb is 1024 bytes.

Based on this, create a function that determines the type of measure.

/*
    1024000 bytes = 1 kilobytes
    1000 kb = 1 megabyte
    1000 mb = 1 gigabyte
    e assim vai..
*/
    function filesize_formatted($path)
    {
        $size = filesize($path);
        $units = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
        $power = $size > 0 ? floor(log($size, 1024)) : 0;
        return number_format($size / pow(1024, $power), 2, '.', ',') . ' ' . $units[$power];
    }

    echo filesize_formatted( 2048 );

In this example, in order to reduce code, we use a mathematical PHP function called pow(), which makes potential expression calculations.

Important, in this example returns the result formatted with 2 decimal places. The formatting of the result may vary with the need of each one. Therefore, be aware and modify according to your need.

More specifically, referring to your code, remove all unnecessary chunk:

// Pega o tamanho do arquivo remoto
$tamanhoarquivo = $filesize;

//
$medidas = array('KB', 'MB', 'GB', 'TB');

/* Se for menor que 1KB arredonda para 1KB */
if($tamanhoarquivo < 999){
$tamanhoarquivo = 1024;
}

for ($i = 0; $tamanhoarquivo > 999; $i++){
$tamanhoarquivo /= 1024;
}

return round($tamanhoarquivo) . $medidas[$i - 1];

Trade for this:

    function filesize_formatted($path)
    {
        $size = filesize($path);
        $units = array( 'B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
        $power = $size > 0 ? floor(log($size, 1024)) : 0;
        return number_format($size / pow(1024, $power), 2, '.', ',') . ' ' . $units[$power];
    }

    return filesize_formatted( $filesize);

0

If the current result was returning in bytes it was only divide the result by 1048576 and you would have it in MB

$tamanhoarquivo = $filesize;     /*Retorna o tamanho do arquivo em bytes*/

Soon:

$tamanhoarquivo = $filesize/1024;     /*Retorna o tamanho do arquivo em kbytes*/

$tamanhoarquivo = $filesize/1048576;  /*Retorna o tamanho do arquivo em Megabytes*/

0


First it is important to define that KB NO is 1024, it was already solved long ago.

To avoid confusion, because Kilo means 1000, they defined the prefix Kibi that has the multiplier 1024. Soon, we have Kib, Mib, Gib and in some operating systems are already using the correct units. IEC Standard Prefixes

Now as for the code, to be able to convert to arbitrary units:

function ConverterPrefixoBinario ($Valor, $UnidadeOrigem, $UnidadeDestino, $Precisão = 2)
{
    $Unidades = array (
        'B' => 1, 
        'KB' => 1000, 'MB' => 1000000, 'GB' => 1000000000, 'TB' => 1000000000,
        'KiB' => 1024, 'MiB' => 1048576, 'GiB' => 1073741824, 'TiB' => 1099511627776
    );

    $ValorBytes = $Valor * $Unidades [$UnidadeOrigem];

    return round($ValorBytes / $Unidades [$UnidadeDestino], $Precisão) . $UnidadeDestino;
}

// 0,15GiB
echo ConverterPrefixoBinario (150, 'MiB', 'GiB');

// 1,5MiB
echo ConverterPrefixoBinario (1572864, 'B', 'MiB');
  • 1

    It is also important to point out that it is somewhat unwise to say so, regarding Kib and KB. Despite the existence of the IEC standard, there is nothing wrong with presenting KB as "Kilobyte", which is also presented as only "K", informally in the technological world. What’s more, by the JEDEC standard, kb is 1024. In practice, the IEC standard on the subject is useless and ignored by industry, except for Apple’s OS-X operating system. Anyway, this is a subject somewhat outside the scope of the question. Of course it’s interesting, but I think there should be a specific topic for such a discussion.

  • Reckless is using a unit where people can misinterpret, JEDEC warns about this: The Specification Notes that These prefixes are included in the Document only to reflect common Usage. It refers to the IEEE/ASTM SI 10-1997 standard as stating, that "this Practice Frequently leads to Confusion and is deprecated".

  • Jesuis.........

  • Ask for 10 people without knowledge in T.I. and 10 others who are beginners in programming to convert Byte to Kbyte... Kib was created to avoid these confusions. As to be useless in the industry, just look that not all HD manufacturers use base 1024 (it has been some years that I do not see Hdds using this base, I myself have a 120GB Kingston SSD which is ~111GiB).

  • sasinhora......

-1

I believe I have reached a solution I leave the code here for those who want to use. I thank Daniel Gomes for the guidelines in the comments.

If someone has some more simplified or different way feel free to put your answer because it will help me in my studies in php.

<?php 


    // Função que verifica o tamanho do arquivo remoto via url

    function remotefileSize($url) {
    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_NOBODY, 1);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 0);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
    curl_setopt($ch, CURLOPT_MAXREDIRS, 3);
    curl_exec($ch);
    $filesize = curl_getinfo($ch, CURLINFO_CONTENT_LENGTH_DOWNLOAD);
    curl_close($ch);

    // Pega o tamanho do arquivo remoto
    $tamanhoarquivo = $filesize;

    //
    $medidas = array('KB', 'MB', 'GB', 'TB');

    /* Se for menor que 1KB arredonda para 1KB */
    if($tamanhoarquivo < 999){
    $tamanhoarquivo = 1024;
    }

    for ($i = 0; $tamanhoarquivo > 999; $i++){
    $tamanhoarquivo /= 1024;
    }

    return round($tamanhoarquivo) . $medidas[$i - 1];
    }

    echo 'O tamamnho do arquivo da url http://thumb.mais.uol.com.br/15233302-medium.jpg e '.remotefileSize('http://thumb.mais.uol.com.br/15233302-medium.jpg');



?>  
  • this is wrong.. 1kb equals 1024 bytes.. however, in comparison checks if it is greater than 999.. .. Another super strange point is the loop of repetition.. without any sense.. and also the round() which makes the result less inaccurate.. Locura locura..

  • 1

    would it be helpful to post a response to what it should be like then ? In case you gave the exact file size to me here.

  • @Rodrigo Veja here

  • 1Kb is not 1024, Kib is 1024, I put in my reply how to make conversion between different units.

  • The @Danielomine method is perfect.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.