How to get the size of a file in PHP?

Use the filesize() function. It returns the size of a file in bytes. If the file does not exist, it gives a warning and returns false.

<?php
file_put_contents("sample.txt", "Hello PHP");

echo filesize("sample.txt") . " bytes";
?>

Output:

Tutorials Class - Output Window

9 bytes

To show the size in KB, divide it by 1024.

<?php
$kb = filesize("sample.txt") / 1024;

echo round($kb, 2) . " KB";
?>

Output:

Tutorials Class - Output Window

0.01 KB

PHP remembers the result of filesize() for the same file. If the file changes during the same script, call clearstatcache() first.


Learn more about the similar topics:
Tutorials
PHP Advanced
PHP File Upload
PHP File Handling
PHP File Inclusion
Exercises & Assignments
No Content Found.
Interview Questions & Answers
What is include() function in PHP?
Can we include a file two times in any PHP page?
Which is the PHP function to delete a file from server?
What is fopen function PHP?
What is the difference between unlink() and unset() in PHP?
How to check if a file exists in PHP?
How to get the size of a file in PHP?