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.
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|falseHere $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.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.