dpc46827 2014-11-07 19:34
浏览 27
已采纳

PHP中字符串的字节大小[重复]

This question already has an answer here:

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...

</div>
  • 写回答

1条回答 默认 最新

  • duandang6352 2014-11-07 20:09
    关注

    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

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?
  • ¥30 求解达问题(有红包)
  • ¥15 请解包一个pak文件