PHPのお勉強!

PHP TOP

filesize

(PHP 4, PHP 5, PHP 7, PHP 8)

filesizeファイルのサイズを取得する

説明

filesize(string $filename): int|false

指定したファイルのサイズを取得します。

パラメータ

filename

ファイルへのパス。

戻り値

ファイルのサイズを返し、エラーの場合は false を返します (また E_WARNING レベルのエラーを発生させます) 。

注意: PHP の数値型は符号付整数であり、 多くのプラットフォームでは 32 ビットの整数を取るため、 ファイルシステム関数の中には 2GB より大きなファイルについては期待とは違う値を返すものがあります。

エラー / 例外

失敗したときは E_WARNING が発生します。

例1 filesize() の例

<?php

// 出力例 somefile.txt: 1024 bytes

$filename = 'somefile.txt';
echo
$filename . ': ' . filesize($filename) . ' bytes';

?>

注意

注意: この関数の結果は キャッシュされます。詳細は、clearstatcache() を参照してください。

ヒント

PHP 5.0.0 以降、この関数は、 何らかの URL ラッパーと組合せて使用することができます。 どのラッパーが stat() ファミリーをサポートしているかを調べるには サポートするプロトコル/ラッパー を参照してください。

参考

  • file_exists() - ファイルまたはディレクトリが存在するかどうか調べる

add a note

User Contributed Notes 33 notes

up
237
rommel at rommelsantor dot com
13 years ago
Extremely simple function to get human filesize.
<?php
function human_filesize($bytes, $decimals = 2) {
$sz = 'BKMGTP';
$factor = floor((strlen($bytes) - 1) / 3);
return
sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}
?>
up
63
Anonymous
13 years ago
if you recently appended something to file, and closed it then this method will not show appended data:
<?php
// get contents of a file into a string
$filename = "/usr/local/something.txt";
$handle = fopen($filename, "r");
$contents = fread($handle, filesize($filename));
fclose($handle);
?>
You should insert a call to clearstatcache() before calling filesize()
I've spent two hours to find that =/
up
10
synnus at gmail dot com
7 years ago
<?php

// Recover all file sizes larger than > 4GB.
// Works on php 32bits and 64bits and supports linux
// Used the com_dotnet extension

function getSize($file) {
$size = filesize($file);
if (
$size <= 0)
if (!(
strtoupper(substr(PHP_OS, 0, 3)) == 'WIN')) {
$size = trim(`stat -c%s $file`);
}
else{
$fsobj = new COM("Scripting.FileSystemObject");
$f = $fsobj->GetFile($file);
$size = $f->Size;
}
return
$size;
}
?>
up
11
evgenij at kostanay dot kz
8 years ago
Slightly edited version of the function from rommel at rommelsantor dot com. Now it returns a two characters file size which is a bit more convenient to read.

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

print
human_filesize(12, 0); // 12B
print human_filesize(1234567890, 4); // 1.1498GB
print human_filesize(123456789, 1); // 117.7MB
print human_filesize(12345678901234, 5); // 11.22833TB
print human_filesize(1234567, 3); // 1.177MB
print human_filesize(123456); // 120.56KB
?>

I removed the P units because strlen doesn't seem to work as expected with integers longer than 14 digits. Though it might be only my system's limitation.
up
4
John Crocker
5 years ago
The first example given may lead one to assume that this function works with a local filename e.g. $fs = filesize("error_log") but if you manually delete some text, then save and close the file, the next time you check filesize("error_log") it will return the original value, because the value is cached for performance reasons. If you didn't know this, it would look like a nasty bug.

So, everyone tells you to insert clearstatcache() which is supposed to clear the cached value and allow you to retrieve the current file size but it still does nothing and looks like another bug!

However, I found that if you always specify the FULL PATH
e.g. $fs = filesize("/user/some/path/error_log");
then clearstatcache() is not even needed.
up
46
Arseny Mogilev
11 years ago
<?php
/**
* Converts bytes into human readable file size.
*
* @param string $bytes
* @return string human readable file size (2,87 Мб)
* @author Mogilev Arseny
*/
function FileSizeConvert($bytes)
{
$bytes = floatval($bytes);
$arBytes = array(
0 => array(
"UNIT" => "TB",
"VALUE" => pow(1024, 4)
),
1 => array(
"UNIT" => "GB",
"VALUE" => pow(1024, 3)
),
2 => array(
"UNIT" => "MB",
"VALUE" => pow(1024, 2)
),
3 => array(
"UNIT" => "KB",
"VALUE" => 1024
),
4 => array(
"UNIT" => "B",
"VALUE" => 1
),
);

foreach(
$arBytes as $arItem)
{
if(
$bytes >= $arItem["VALUE"])
{
$result = $bytes / $arItem["VALUE"];
$result = str_replace(".", "," , strval(round($result, 2)))." ".$arItem["UNIT"];
break;
}
}
return
$result;
}

?>
up
9
ivijan dot stefan at gmail dot com
7 years ago
This function also can be great for browser caching controll. For example, you have a stylesheet and you want to make sure everyone has the most recent version. You could rename it every time you edit it, but that would be a waste of time. Instead, you can do like:

<?php

echo '<link rel="stylesheet" href="style.css?ver=1.'.filesize(dirname(__FILE__).'/style.css').'.'.filemtime(dirname(__FILE__).'/style.css').'.0">';

?>

Sample output:

<link rel="stylesheet" href="style.css?ver=1.8824.1499869132.0">

This also can be apply for JS and also images with same name.
up
3
honza dot kuchar at grifart dot cz
8 years ago
For files bigger then 2 GB use my library called Big File Tools. https://github.com/jkuchar/BigFileTools. More details on stackoverflow: http://stackoverflow.com/a/35233556/631369
up
15
Damien Dussouillez
7 years ago
<?php
/**
* Return file size (even for file > 2 Gb)
* For file size over PHP_INT_MAX (2 147 483 647), PHP filesize function loops from -PHP_INT_MAX to PHP_INT_MAX.
*
* @param string $path Path of the file
* @return mixed File size or false if error
*/
function realFileSize($path)
{
if (!
file_exists($path))
return
false;

$size = filesize($path);

if (!(
$file = fopen($path, 'rb')))
return
false;

if (
$size >= 0)
{
//Check if it really is a small file (< 2 GB)
if (fseek($file, 0, SEEK_END) === 0)
{
//It really is a small file
fclose($file);
return
$size;
}
}

//Quickly jump the first 2 GB with fseek. After that fseek is not working on 32 bit php (it uses int internally)
$size = PHP_INT_MAX - 1;
if (
fseek($file, PHP_INT_MAX - 1) !== 0)
{
fclose($file);
return
false;
}

$length = 1024 * 1024;
while (!
feof($file))
{
//Read the file until end
$read = fread($file, $length);
$size = bcadd($size, $length);
}
$size = bcsub($size, $length);
$size = bcadd($size, strlen($read));

fclose($file);
return
$size;
}
up
7
synnus at gmail dot com
8 years ago
// best converting the negative number with File Size .
// does not work with files greater than 4GB
//
// specifically for 32 bit systems. limit conversions filsize is 4GB or
// 4294967296. why we get negative numbers? by what the file
// pointer of the meter must work with the PHP MAX value is 2147483647.
// Offset file : 0 , 1 , 2 , 3 , ... 2147483647 = 2GB
// to go higher up the 4GB negative numbers are used
// and therefore after 2147483647, we will -2147483647
// -2147483647, -2147483646, -2147483645, -2147483644 ... 0 = 4GB
// therefore 0, 2147483647 and -2147483647 to 0. all done 4GB = 4294967296
// the first offset to 0 and the last offset to 0 of 4GB should be added in
// your compute, so "+ 2" for the number of bytes exate .

<?php
function filsize_32b($file) {
$filez = filesize($file);
if(
$filez < 0) { return (($filez + PHP_INT_MAX) + PHP_INT_MAX + 2); }
else { return
$filez; }
}
?>
up
16
CertaiN
10 years ago
The simplest and most efficient implemention for getting remote filesize:

<?php
function remote_filesize($url) {
static
$regex = '/^Content-Length: *+\K\d++$/im';
if (!
$fp = @fopen($url, 'rb')) {
return
false;
}
if (
isset(
$http_response_header) &&
preg_match($regex, implode("\n", $http_response_header), $matches)
) {
return (int)
$matches[0];
}
return
strlen(stream_get_contents($fp));
}
?>
up
5
aidan at php dot net
19 years ago
This function quickly calculates the size of a directory:
http://aidanlister.com/repos/v/function.dirsize.php

You can convert filesizes to a human readable size using:
http://aidanlister.com/repos/v/function.size_readable.php

For a faster (unix only) implementation, see function.disk-total-space, note #34100
http://www.php.net/manual/en/function.disk-total-space.php#34100

Also of interest is this wikipedia article, discussing the difference between a kilobyte (1000) and a kibibyte (1024).
http://en.wikipedia.org/wiki/Bytes
up
11
C0nw0nk
8 years ago
Here is my super fast method of getting >2GB files to output the correct byte size on any version of windows works with both 32Bit and 64Bit.

<?php
function find_filesize($file)
{
if(
substr(PHP_OS, 0, 3) == "WIN")
{
exec('for %I in ("'.$file.'") do @echo %~zI', $output);
$return = $output[0];
}
else
{
$return = filesize($file);
}
return
$return;
}

//Usage : find_filesize("path");
//Example :
echo "File size is : ".find_filesize("D:\Server\movie.mp4")."";
?>
up
3
synnus at gmail dot com
8 years ago
// extract filesize with command dir windows 10
// is ok for all system 32/64 and the best compatibility for Dummy file
// but cant return value in (int) for best return use Float

<?php

filesize_dir
("d:\\test.mkv"); //11.5GB => return (float) 12401880207

function filesize_dir($file) {
exec('dir ' . $file, $inf);
$size_raw = $inf[6];
$size_exp = explode(" ",$size_raw);
$size_ext = $size_exp[19];
$size_int = (float) str_replace(chr(255), '', $size_ext);
return
$size_int;
}

?>
up
6
Anonymous
11 years ago
This functions returns the exact file size for file larger than 2 GB on 32 bit OS:

<?php
function file_get_size($file) {
//open file
$fh = fopen($file, "r");
//declare some variables
$size = "0";
$char = "";
//set file pointer to 0; I'm a little bit paranoid, you can remove this
fseek($fh, 0, SEEK_SET);
//set multiplicator to zero
$count = 0;
while (
true) {
//jump 1 MB forward in file
fseek($fh, 1048576, SEEK_CUR);
//check if we actually left the file
if (($char = fgetc($fh)) !== false) {
//if not, go on
$count ++;
} else {
//else jump back where we were before leaving and exit loop
fseek($fh, -1048576, SEEK_CUR);
break;
}
}
//we could make $count jumps, so the file is at least $count * 1.000001 MB large
//1048577 because we jump 1 MB and fgetc goes 1 B forward too
$size = bcmul("1048577", $count);
//now count the last few bytes; they're always less than 1048576 so it's quite fast
$fine = 0;
while(
false !== ($char = fgetc($fh))) {
$fine ++;
}
//and add them
$size = bcadd($size, $fine);
fclose($fh);
return
$size;
}
?>
up
6
Supermagnus
16 years ago
<?php
function getSizeFile($url) {
if (
substr($url,0,4)=='http') {
$x = array_change_key_case(get_headers($url, 1),CASE_LOWER);
if (
strcasecmp($x[0], 'HTTP/1.1 200 OK') != 0 ) { $x = $x['content-length'][1]; }
else {
$x = $x['content-length']; }
}
else {
$x = @filesize($url); }

return
$x;
}
?>

In case of you have a redirection in the server (like Redirect Permanent in the .htaccess)

In this case we have for exemple:
[content-length] => Array

(

[0] => 294 // Size requested file

[1] => 357556 // Real Size redirected file

)
up
1
PHP-Hasan
5 years ago
Under Windows 10 filesize obviously cannot work with relative path names. Use absolute path instead. $size = filesize(".\\myfile.txt"); does not work for me while "d:\\MyFiles\\Myfile.txt" will do. The same applys to similar functions like is_file() or stat(). They won't work correctly unless given an absolute path.
up
4
synnus at gmail dot com
8 years ago
// use system windows for give filesize
// best for php 32bit or php 64bit
// I do not know if it works on other windows, but on Windows 10 works well here

<?php

echo filesize_cmd('c:\\', 'log.txt'); //return 1135

function filesize_cmd($folder, $file) {
return
exec('forfiles /p '.$folder.' /m "'.$file.'" /c "cmd /c echo @fsize"');
}

?>
up
2
mbh789 at gmail dot com
7 years ago
function dir_size($file) {
//tested on win 7x64 php 5.4
exec('dir /s /a "' . $file.'"', $inf);
$r=explode(' ',$inf[count($inf)-2]);
$rr = preg_replace('~[^\d]+~','',$r[count($r)-2]);
return $rr;
}