Backend Development 4 min read

PHP filesize() Function: Syntax, Parameters, Return Values, Examples, and Usage Tips

This article explains the PHP filesize() function, covering its prototype, required $filename parameter, possible return values, practical code examples, important usage considerations, and extended applications such as checking for empty files.

php中文网 Courses
php中文网 Courses
php中文网 Courses
PHP filesize() Function: Syntax, Parameters, Return Values, Examples, and Usage Tips

Function Prototype

<code>filesize(string $filename): int|false</code>

Parameter Description

$filename : required, the path to the file whose size is to be obtained.

Return Value

If successful, returns the file size in bytes.

If the operation fails, returns false .

Function Example

<code>$filename = 'path/to/file.txt';
$filesize = filesize($filename);
if ($filesize !== false) {
    echo "文件大小为:" . $filesize . " 字节";
} else {
    echo "无法获取文件大小";
}
</code>

Usage Notes

The file path must be a valid absolute or relative path.

If the file does not exist or is inaccessible, filesize() returns false .

The size is expressed in bytes.

If the file size exceeds PHP's integer limit (commonly 2 GB), filesize() may return a negative number.

Example Explanation

Assuming a file file.txt located at path/to/file.txt contains the text "Hello, World!" (13 bytes), the following code obtains and prints its size:

<code>$filename = 'path/to/file.txt'; // 文件路径
$filesize = filesize($filename); // 获取文件大小
if ($filesize !== false) {
    echo "文件大小为:" . $filesize . " 字节"; // 输出文件大小
} else {
    echo "无法获取文件大小"; // 输出错误信息
}
</code>

The output will be: "文件大小为:13 字节".

Extended Application

The filesize() function can also be used to determine whether a file is empty.

<code>$filename = 'path/to/empty.txt';
$filesize = filesize($filename);
if ($filesize === 0) {
    echo "文件为空";
} else {
    echo "文件不为空";
}
</code>

Summary

The filesize() function is a practical PHP utility for obtaining a file's size in bytes, enabling developers to handle files based on their size. However, when dealing with very large files, performance considerations may arise, and alternative methods might be preferable.

backendPHPfilesystemfile sizefilesize
php中文网 Courses
Written by

php中文网 Courses

php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.