PHP filesize

Summary: in this tutorial, you will learn how to use the PHP filesize() function to get the size of a file.

Introduction to the PHP filesize() function

The filesize() function returns the size of a given file in bytes:

filesize ( string $filename ) : int|falseCode language: PHP (php)

The filesize() function returns the size of the file specified by the $filename in bytes. In case of an error, the function returns false.

PHP filesize() function example

The following example uses the filesize() function to get the size of the readme.txt file in bytes:

<?php

$filename = 'readme.txt';
echo $filename,': ', filesize($filename),' bytes';Code language: HTML, XML (xml)

Output:

readme.txt: 19 bytesCode language: CSS (css)

In practice, you will rarely use the bytes for showing the size of the file. To get the human-readable size of a file, you can use the following function:

function format_filesize(int $bytes, int $decimals = 2): string
{
    $units = 'BKMGTP';
    $factor = floor((strlen($bytes) - 1) / 3);

    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . $units[(int)$factor];
}
Code language: PHP (php)

Summary

  • Use the PHP filesize() function to get the size of a file in bytes.
Did you find this tutorial useful?