How to Get File Size in Bytes with PHP filesize

This article explains how to retrieve the size of a local file in bytes using PHP’s built-in filesize() function. It covers the basic syntax, provides a practical code example, and explains important considerations such as error handling and clearing the file status cache for accurate results.

Basic Syntax

The filesize() function in PHP accepts a single string parameter representing the path to the file and returns the file size in bytes as an integer. If the file cannot be accessed or does not exist, the function returns false and generates an E_WARNING level error.

filesize(string $filename): int|false

Practical Code Example

To avoid PHP warnings, it is best practice to check if the file exists using file_exists() before calling filesize().

<?php
$filename = 'document.txt';

// Check if the file exists before attempting to get its size
if (file_exists($filename)) {
    $file_size = filesize($filename);
    
    if ($file_size !== false) {
        echo "The file size of '$filename' is " . $file_size . " bytes.";
    } else {
        echo "Failed to retrieve the file size.";
    }
} else {
    echo "The file '$filename' does not exist.";
}
?>

Important Considerations

1. Clearing the Stat Cache

PHP caches the results of file system functions, including filesize(), to improve performance. If a file is being modified or written to during the execution of the same script, filesize() may return outdated cached data. To ensure you get the current size, call clearstatcache() before calling filesize().

<?php
clearstatcache();
$file_size = filesize($filename);
?>

2. File Size Limit on 32-bit Systems

On 32-bit systems, PHP’s integer type is signed and limited to 2 GB. If you attempt to use filesize() on a file larger than 2 GB on a 32-bit platform, it may return incorrect results or fail. On 64-bit platforms, the function safely supports files up to 9 Exabytes.