1

I have an encrypted image and before saving it I would like to know how much space it takes up. I can get the number of characters via strlen($img) or via mb_strlen($img) but I would like to get a number like 16KiB (or KB).

I then save the string into a MySQL database in blob format, where I can see the size of it using PhpMyAdmin.

EDIT If I use strlen to get the byte size of the string (which I want) I get a different value from the byte size displayed in my MySQL database (where the string is not saved as a char but as a blog, meaning binary). How can this be? And how can I find out how large the binary size will be when I save the string in the database.

I save the string simply with the MySQL command

INSERT INTO table (content, bla) VALUES ($string, bla); (not fully correct but for example purpose – this works when correct)

Now when I look inside my database it displays me a size e.g 315 KB but when I take $string and do strlen on it, it returns something like 240000 (Not the same in bits as in KB)

I will investigate my self...

Deproblemify
  • 3,340
  • 5
  • 26
  • 41

1 Answers1

1

This does essentially the same thing as Dany's answer, but a little more compact.

function human_filesize($bytes, $decimals = 2) {
    $size = array('B','kB','MB','GB','TB','PB','EB','ZB','YB');
    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$size[$factor];
}

echo human_filesize(filesize($filename));

Source: http://jeffreysambells.com/2012/10/25/human-readable-filesize-php

Curtis Mattoon
  • 4,642
  • 2
  • 27
  • 34