0
0
PhpHow-ToBeginner · 3 min read

How to Get File Size in PHP: Simple Guide with Examples

In PHP, you can get the size of a file using the filesize() function by passing the file path as an argument. It returns the file size in bytes as an integer.
📐

Syntax

The filesize() function takes one parameter, the path to the file, and returns its size in bytes as an integer.

  • Parameter: filename - The path to the file you want to check.
  • Return: File size in bytes or false on failure.
php
int filesize ( string $filename )
💻

Example

This example shows how to get the size of a file named example.txt and print it in bytes.

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

if (file_exists($filename)) {
    $size = filesize($filename);
    echo "The size of '$filename' is $size bytes.";
} else {
    echo "File does not exist.";
}
?>
Output
The size of 'example.txt' is 1234 bytes.
⚠️

Common Pitfalls

Common mistakes when using filesize() include:

  • Passing a wrong or non-existent file path, which causes filesize() to return false.
  • Not checking if the file exists before calling filesize(), leading to warnings.
  • Expecting the size in kilobytes or megabytes directly; filesize() returns bytes, so you need to convert it manually.
php
<?php
// Wrong way: no file existence check
$size = filesize('missing.txt'); // Warning and false

// Right way: check file existence first
if (file_exists('missing.txt')) {
    $size = filesize('missing.txt');
} else {
    echo 'File not found.';
}
?>
📊

Quick Reference

FunctionDescriptionReturn Value
filesize(string $filename)Returns size of file in bytesint (bytes) or false on failure
file_exists(string $filename)Checks if file existsbool
Example conversionConvert bytes to KBsize_in_bytes / 1024

Key Takeaways

Use filesize() with a valid file path to get file size in bytes.
Always check if the file exists with file_exists() before calling filesize().
filesize() returns bytes; convert to KB or MB manually if needed.
Passing an invalid path causes filesize() to return false and may trigger warnings.
Use simple arithmetic to convert bytes to larger units for easier reading.