获取使用file_put_contents创建的文件大小

时间:2012-04-16 20:49:52

标签: php

我使用 file_put_contents 上传文件。我有没有办法计算文件大小,就像我们使用* move_uploaded_file *一样?我相信字符串长度和file_size是两个不同的东西。

2 个答案:

答案 0 :(得分:5)

根据与file_put_contents返回值相关的文档:

  

该函数返回写入文件的字节数,或者失败时返回FALSE。

所以你应该能够做到这样的事情:

$filesize = file_put_contents($myFile, $someData);

答案 1 :(得分:1)

有一个名为filesize()的函数可以计算文件的大小。您将文件路径作为参数传递:

$filesize = filesize("myfiles/file.txt");

然后,您可以使用这样的函数来格式化文件大小,使其更加用户友好:

function format_bytes($a_bytes) {
    if ($a_bytes < 1024) {
        return $a_bytes .' B';
    } elseif ($a_bytes < 1048576) {
        return round($a_bytes / 1024, 2) .' KB';
    } elseif ($a_bytes < 1073741824) {
        return round($a_bytes / 1048576, 2) . ' MB';
    } elseif ($a_bytes < 1099511627776) {
        return round($a_bytes / 1073741824, 2) . ' GB';
    } elseif ($a_bytes < 1125899906842624) {
        return round($a_bytes / 1099511627776, 2) .' TB';
    } elseif ($a_bytes < 1152921504606846976) {
        return round($a_bytes / 1125899906842624, 2) .' PB';
    } elseif ($a_bytes < 1180591620717411303424) {
        return round($a_bytes / 1152921504606846976, 2) .' EB';
    } elseif ($a_bytes < 1208925819614629174706176) {
        return round($a_bytes / 1180591620717411303424, 2) .' ZB';
    } else {
        return round($a_bytes / 1208925819614629174706176, 2) .' YB';
    }
}
相关问题