Backend Development 3 min read

How to Use PHP’s filesize() Function to Get File Size

This article explains the PHP filesize() function, its syntax, usage examples, and important considerations such as checking file existence and handling failures, providing developers with a clear guide to retrieve local file sizes in bytes.

php中文网 Courses
php中文网 Courses
php中文网 Courses
How to Use PHP’s filesize() Function to Get File Size

In PHP development we often need to obtain a file's size, and PHP provides a convenient filesize() function for this purpose.

Usage:

The filesize() function is simple to use. Its basic syntax is:

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

The $filename parameter specifies the path to the file whose size you want to retrieve. The function returns the size in bytes, or false on failure.

Code Example:

The following example demonstrates how to use filesize() to get a file's size:

<code>$filename = 'file.txt';

if (file_exists($filename)) {
    $filesize = filesize($filename);
    echo '文件 ' . $filename . ' 的大小为 ' . $filesize . ' 字节。';
} else {
    echo '文件 ' . $filename . ' 不存在。';
}
</code>

In this example we first set the file path, check its existence with file_exists() , then call filesize() to obtain the size and output it; if the file does not exist we output an error message.

Note: filesize() works only for local files; it cannot retrieve the size of remote files. To get remote file sizes you need other methods such as cURL or an HTTP HEAD request. The size is returned in bytes, and you can convert it to KB, MB, etc., with simple calculations.

Conclusion:

The filesize() function is a handy PHP tool for quickly obtaining a file's size, simplifying file‑handling tasks in development.

backend developmentphpfile sizephp-functionsfilesize
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.