PHP filesize() 函数

filesize

作用:函数返回指定文件的大小

语法:

filesize(filename)

参数:

filename:必需。规定要检查的文件。

返回值:

返回文件大小的字节数,如果出错返回 FALSE 并生成一条 E_WARNING 级的错误。

filesize 示例

示例一

  1. <?php
  2. // 输出类似:somefile.txt: 1024 bytes
  3. $filename = 'somefile.txt';
  4. echo $filename . ': ' . filesize($filename) . ' bytes';
  5. ?>

示例二

  1. <?php
  2. function human_filesize($bytes, $decimals = 2) {
  3. $sz = 'BKMGTP';
  4. $factor = floor((strlen($bytes) - 1) / 3);
  5. return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
  6. }
  7. ?>

示例三

  1. <?php
  2. /**
  3. * Converts bytes into human readable file size.
  4. *
  5. * @param string $bytes
  6. * @return string human readable file size (2,87 Мб)
  7. * @author Mogilev Arseny
  8. */
  9. function FileSizeConvert($bytes)
  10. {
  11. $bytes = floatval($bytes);
  12. $arBytes = array(
  13. 0 => array(
  14. "UNIT" => "TB",
  15. "VALUE" => pow(1024, 4)
  16. ),
  17. 1 => array(
  18. "UNIT" => "GB",
  19. "VALUE" => pow(1024, 3)
  20. ),
  21. 2 => array(
  22. "UNIT" => "MB",
  23. "VALUE" => pow(1024, 2)
  24. ),
  25. 3 => array(
  26. "UNIT" => "KB",
  27. "VALUE" => 1024
  28. ),
  29. 4 => array(
  30. "UNIT" => "B",
  31. "VALUE" => 1
  32. ),
  33. );
  34. foreach($arBytes as $arItem)
  35. {
  36. if($bytes >= $arItem["VALUE"])
  37. {
  38. $result = $bytes / $arItem["VALUE"];
  39. $result = str_replace(".", "," , strval(round($result, 2)))." ".$arItem["UNIT"];
  40. break;
  41. }
  42. }
  43. return $result;
  44. }
  45. ?>

示例四

  1. <?php
  2. /**
  3. * Return file size (even for file > 2 Gb)
  4. * For file size over PHP_INT_MAX (2 147 483 647), PHP filesize function loops from -PHP_INT_MAX to PHP_INT_MAX.
  5. *
  6. * @param string $path Path of the file
  7. * @return mixed File size or false if error
  8. */
  9. function realFileSize($path)
  10. {
  11. if (!file_exists($path))
  12. return false;
  13. $size = filesize($path);
  14. if (!($file = fopen($path, 'rb')))
  15. return false;
  16. if ($size >= 0)
  17. {//Check if it really is a small file (< 2 GB)
  18. if (fseek($file, 0, SEEK_END) === 0)
  19. {//It really is a small file
  20. fclose($file);
  21. return $size;
  22. }
  23. }
  24. //Quickly jump the first 2 GB with fseek. After that fseek is not working on 32 bit php (it uses int internally)
  25. $size = PHP_INT_MAX - 1;
  26. if (fseek($file, PHP_INT_MAX - 1) !== 0)
  27. {
  28. fclose($file);
  29. return false;
  30. }
  31. $length = 1024 * 1024;
  32. while (!feof($file))
  33. {//Read the file until end
  34. $read = fread($file, $length);
  35. $size = bcadd($size, $length);
  36. }
  37. $size = bcsub($size, $length);
  38. $size = bcadd($size, strlen($read));
  39. fclose($file);
  40. return $size;
  41. }