Master PHP’s filesize() Function: Quick Guide & Code Examples

Learn how to use PHP’s built-in filesize() function to retrieve file sizes in bytes, understand its syntax, see practical code examples with file existence checks, and discover important considerations such as handling local files only and converting sizes to readable formats.

php Courses
php Courses
php Courses
Master PHP’s filesize() Function: Quick Guide & Code Examples

Usage

The usage of filesize() is very simple. Below is its basic syntax: filesize(string $filename): int|false Here $filename specifies the path of the file whose size is to be retrieved. The function returns the file size in bytes, or false on failure.

Code Example

The following example demonstrates how to use filesize() to obtain a file’s size:

$filename = 'file.txt';

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

The script first sets the file path, uses file_exists() to verify existence, then calls filesize() to get the size and prints it. If the file is missing, an error message is displayed.

Note: filesize() works only for local files; it cannot retrieve the size of remote files. To obtain remote file sizes, use cURL or send an HTTP HEAD request. The size is returned in bytes; you can convert it to KB, MB, etc., with simple arithmetic.

Conclusion

The filesize() function provides a straightforward way to obtain file size information in PHP, simplifying file‑handling tasks in backend development.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

PHPCode Examplefile-handlingfilesize
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

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.