PHP文件大小超过4Gb



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

CCD_ 1仅适用于<2Gb
CCD_ 2仅适用于<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;
}

有什么想法吗?

您正在溢出PHP的32位整数。在*nix上,这将为您提供字符串形式的文件大小:

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

执行一个shell命令怎么样,比如:

<?php
echo shell_exec("du 'PATH_TO_FILE'");
?>

其中PATH_TO_FILE显然是相对于php脚本的文件路径

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

11777928    name_of_file.extention

这里有一个完整的解决方案,您可以尝试: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);

此函数可以在32位Linux 上运行

function my_file_size($file){
    if ( PHP_INT_MAX > 2147483647){  //64bit
        return  filesize($file);
    }
    $ps_cmd = "/bin/ls -l $file";
    exec($ps_cmd, $arr_output, $rtn);
    ///bin/ls -l /data/07f2088a371424c0bdcdca918a3008a9cbd74a25.ic2
    //-rw-r--r-- 1 resin resin 269484032 9月   9 21:36 /data/07f2088a371424c0bdcdca918a3008a9cbd74a25.ic2
    if($rtn !=0) return floatval(0);
    preg_match("/^[^s]+s+d+s+[^s]+s+[^s]+s+(d+)s+/", $arr_output[0], $matches);
    if(!empty($matches)){
        return  floatval($matches[1]);
    }
    return floatval(0);
}

最新更新