Using PHP's filesize() Function to Retrieve and Convert File Sizes

This article explains how to use PHP's built-in filesize() function to retrieve a file's size in bytes, demonstrates checking for errors, and shows how to convert the result to kilobytes using division and the round() function.

php Courses
php Courses
php Courses
Using PHP's filesize() Function to Retrieve and Convert File Sizes

In PHP development, we often need to obtain a file's size, which requires the built‑in function filesize(). The filesize() function returns the size of a file in bytes.

The basic syntax of filesize() is: filesize(string $filename): int|false Here $filename is the name of the file whose size you want, which can be a local path or a remote URL. The function returns an integer representing the size in bytes, or false on failure.

Example: suppose we have a file test.txt and we want to get its size.

$filename = 'test.txt';
$size = filesize($filename);

if ($size !== false) {
    echo "文件的大小是:" . $size . " 字节";
} else {
    echo "获取文件大小失败";
}

The code calls filesize() to store the size of test.txt in $size, checks whether $size is not false, and prints the size in bytes if successful; otherwise it prints an error message.

Note that the size returned by filesize() is in bytes. To convert it to other units such as kilobytes, divide by 1024. For example:

$filename = 'test.txt';
$size = filesize($filename);

if ($size !== false) {
    $size_kb = round($size / 1024, 2);
    echo "文件的大小是:" . $size_kb . " KB";
} else {
    echo "获取文件大小失败";
}

In this snippet the file size is divided by 1024 and the round() function is used to keep two decimal places, storing the result in $size_kb, which is then printed with the KB unit.

Summary

The filesize() function is a practical PHP utility for quickly obtaining a file's size; developers can use it to retrieve the size in bytes and, by dividing by 1024 and optionally rounding, convert the value to kilobytes or other units as needed.

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.

PHPfilesize
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.