1

我正在使用file_put_contents上传文件。有什么方法可以像使用 *move_uploaded_file* 一样计算文件大小?我相信字符串长度和文件大小是两个不同的东西。

4

2 回答 2

5

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

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

因此,您应该能够执行以下操作:

$filesize = file_put_contents($myFile, $someData);
于 2012-04-16T20:52:15.507 回答
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';
    }
}
于 2012-04-16T21:02:55.207 回答