2012-04-16 103 views
0

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

+0

字符串就是一个的字节序列定义长度。因此,如果你将一个文件的所有内容读入一个字符串,那么strlen应该返回该文件的字节数...... – crush 2012-04-16 20:52:46

+0

用'file_put_content'的'$ filename'参数调用'file_size'。 – miqbal 2012-04-16 21:01:14

回答

4

根据有关file_put_contents返回值文档:

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

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

$filesize = file_put_contents($myFile, $someData); 
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'; 
    } 
}