2011-06-26 54 views
5

我正在运行Synology NAS服务器, ,我试图使用PHP来获取文件的文件大小。
我试图找到一个函数,将成功计算4Gb以上的文件的文件大小。通过4Gb的PHP文件大小

filesize($file);仅适用于文件<的2Gb
sprintf("%u", filesize($file));仅适用于文件<的4Gb

我也试过其他功能,我在PHP手册中发现,但它不能正常工作。
它随机适用于某些文件大小,但不适用于其他文件。

function fsize($file) { 
    // filesize will only return the lower 32 bits of 
    // the file's size! Make it unsigned. 
    $fmod = filesize($file); 
    if ($fmod < 0) $fmod += 2.0 * (PHP_INT_MAX + 1); 

    // find the upper 32 bits 
    $i = 0; 

    $myfile = fopen($file, "r"); 

    // feof has undefined behaviour for big files. 
    // after we hit the eof with fseek, 
    // fread may not be able to detect the eof, 
    // but it also can't read bytes, so use it as an 
    // indicator. 
    while (strlen(fread($myfile, 1)) === 1) { 
    fseek($myfile, PHP_INT_MAX, SEEK_CUR); 
    $i++; 
    } 

    fclose($myfile); 

    // $i is a multiplier for PHP_INT_MAX byte blocks. 
    // return to the last multiple of 4, as filesize has modulo of 4 GB (lower 32 bits) 
    if ($i % 2 == 1) $i--; 

    // add the lower 32 bit to our PHP_INT_MAX multiplier 
    return ((float)($i) * (PHP_INT_MAX + 1)) + $fmod; 
} 

任何想法?

回答

11

您正在溢出PHP的32位整数。在* nix中,这会给你的文件大小为一个字符串:

<?php $size = trim(shell_exec('stat -c %s '.escapeshellarg($filename))); ?> 
1

如何像执行shell命令:

<?php 

echo shell_exec("du 'PATH_TO_FILE'"); 

?> 

其中文件路径是明显的路径相对于PHP脚本

文件,你很可能会做一些正则表达式来获得文件大小为因为它返回一个字符串,如:

11777928 name_of_file.extention 
+0

当我尝试只是呼应,它说警告:了shell_exec ():无法在安全模式下在/volume1/web/required/function.php行153上使用反引号。我尝试更改安全模式开启/关闭 – Richard

0

这是一个完整的解决方案,你可以尝试什么:https://stackoverflow.com/a/48363570/2592415

include_once 'class.os.php'; 
include_once 'function.filesize.32bit.php'; 

// Must be real path to file 
$file = "/home/username/some-folder/yourfile.zip"; 
echo get_filesize($file);