PHP filesize() Function

PHP

PHP filesize() - Get File Size

Welcome to this comprehensive tutorial on the PHP filesize() function. If you work with PHP and need to determine the size of files for storage management, bandwidth calculation, or validation purposes, then mastering filesize() is essential. With over 14 years of experience in PHP file processing, I’ll guide you step-by-step through its usage, examples, best practices, common pitfalls, and even prepare you for interviews with targeted questions and answers.

Introduction

The filesize() function in PHP returns the size of a file in bytes. It is part of PHP’s standard filesystem functions and helps you quickly retrieve the size of any accessible file on your server. Whether you're validating user-uploaded files or monitoring disk usage, filesize() is a handy and lightweight tool.

Prerequisites

  • Basic knowledge of PHP (variables, functions)
  • Access to a PHP runtime (local or server environment)
  • Familiarity with filesystem paths (relative and absolute)
  • Files available on your server to check the size

Setup Steps

  1. Install PHP on your local machine or ensure your server supports PHP.
  2. Create or use an existing file on which to test the filesize.
  3. Write a PHP script to invoke the filesize() function.
  4. Execute the script and check the output.

Understanding syntax of filesize()


int filesize ( string $filename )
  

Parameters:

  • $filename : Path to the file (relative or absolute)

Return value: The file size in bytes on success, or FALSE on failure.

Simple Example

Below is a basic example to get the size of a file named example.txt located in the same directory as your script:

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

$filesize = filesize($filename);

if ($filesize !== false) {
    echo "Size of "$filename" is $filesize bytes.";
} else {
    echo "Could not get the size of the file.";
}
?>

Detailed Explained Examples

Example 1: Checking file size with error handling

<?php
$filename = 'upload/image.png';

if (file_exists($filename)) {
    $size = filesize($filename);
    if ($size !== false) {
        echo "File size: $size bytes";
    } else {
        echo "Error: Unable to retrieve file size.";
    }
} else {
    echo "File does not exist.";
}
?>

This shows how to use file_exists() alongside filesize() to prevent errors.

Example 2: Converting file size to human-readable format

<?php
function human_filesize($bytes, $decimals = 2) {
    $sizes = ['B', 'KB', 'MB', 'GB', 'TB'];
    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . " " . $sizes[$factor];
}

$filename = 'report.pdf';
if (file_exists($filename)) {
    $size = filesize($filename);
    echo "File size: " . human_filesize($size);
} else {
    echo "File not found.";
}
?>

Example 3: Using filesize() in upload validation

<?php
if (isset($_FILES['userfile'])) {
    $tmpName = $_FILES['userfile']['tmp_name'];
    $maxSize = 2 * 1024 * 1024; // 2MB upload limit

    $fileSize = filesize($tmpName);
    if ($fileSize !== false && $fileSize <= $maxSize) {
        echo "Upload accepted. File size: $fileSize bytes.";
    } else {
        echo "Upload failed. File size exceeds the 2MB limit.";
    }
}
?>

Best Practices

  • Always check file existence: Use file_exists() before calling filesize() to avoid errors.
  • Handle false returns: filesize() returns FALSE on failure; handle this gracefully.
  • Validate user inputs: When using filesize() on user-uploaded files, verify the values thoroughly.
  • Beware of caching: PHP may cache file metadata, so calling clearstatcache() before filesize() can ensure up-to-date size info.
  • Use human-readable formats: For better UX, convert bytes into KB/MB etc. as shown in examples.

Common Mistakes

  • Not checking if the file exists before calling filesize(), which results in warnings.
  • Assuming filesize() always returns integer; it can return FALSE.
  • Reading filesize of directories; filesize() only works correctly on files, not directories.
  • Not accounting for caching, leading to outdated file size results.
  • Passing invalid or broken file paths.

Interview Questions

Junior-Level Questions

  • What does the PHP filesize() function do?
    It returns the size of a file in bytes.
  • What type of value does filesize() return on success?
    An integer representing the file size in bytes.
  • What will filesize() return if the file does not exist?
    It returns FALSE.
  • Can filesize() be used on directories?
    No, it is meant for files only; directory sizes are not reliably returned.
  • Why should you check if the file exists before using filesize()?
    To avoid warnings and errors if the file is missing.

Mid-Level Questions

  • How can you get an up-to-date file size if you suspect caching issues?
    Call clearstatcache() before filesize() to clear PHP’s cached file stats.
  • Explain how to convert bytes returned by filesize() into human-readable formats.
    Divide the bytes by powers of 1024 and label as KB, MB, GB, etc., formatting the number as needed.
  • What are some practical applications of using filesize() in PHP projects?
    File upload validation, disk space monitoring, bandwidth estimation, and logging file details.
  • Is the file path passed to filesize() case-sensitive?
    It depends on the underlying filesystem (e.g., Windows is case-insensitive, Linux is case-sensitive).
  • What happens if you try to get the filesize of a file that your PHP script does not have permission to read?
    filesize() will return FALSE due to permission denial.

Senior-Level Questions

  • How would you optimize the use of filesize() in a high-traffic PHP application?
    Minimize calls by caching file sizes in memory or a faster store and use clearstatcache() only when necessary to maintain performance.
  • Describe how symbolic links might affect filesize() results.
    filesize() reports the size of the linked file, but if the link is broken or inaccessible, it returns FALSE.
  • Discuss differences in filesize reporting between 32-bit and 64-bit PHP systems.
    On 32-bit systems, very large files (larger than 2GB) may cause filesize() to return incorrect or negative values due to integer overflow, which is fixed on 64-bit systems.
  • How would you implement reliable file size checks during large file uploads asynchronously?
    Use filesize() on temporary files after upload completion or leverage streaming APIs and chunked uploads to validate size progressively.
  • Explain how to handle cross-platform differences when retrieving file sizes using filesize().
    Account for case sensitivity in file paths, different filesystem behaviors, and ensure correct error handling since behavior might differ between Windows and Unix-based systems.

Frequently Asked Questions (FAQ)

Q1: Does filesize() measure file size in bytes or other units?

It always returns the file size in bytes.

Q2: What can cause filesize() to return FALSE?

The file may not exist, your script might lack permissions, or the path could be invalid.

Q3: Can filesize() return accurate sizes for very large files?

On 64-bit PHP builds, yes. On 32-bit systems, it might fail due to integer size limitations.

Q4: Should I always use clearstatcache() before calling filesize()?

Not always. Use it if you suspect that file changes are not reflected due to PHP’s caching of file stats.

Q5: Is filesize() affected by file compression?

filesize() returns the actual size of the stored file, regardless of whether it’s compressed or not.

Q6: Can filesize() be used with URLs or remote files?

No, filesize() works only with local files on the server.

Q7: How to get file size in KB or MB?

Use appropriate divisions by 1024 and format the output (see the human-readable format example).

Q8: Does changing file permissions affect filesize()?

If the PHP process cannot access the file due to permissions, filesize() will fail, even if the file exists.

Q9: How do I avoid warnings from filesize() when the file doesn’t exist?

Check with file_exists() before calling filesize().

Q10: Is filesize() suitable for checking file size before download?

Yes, it’s commonly used to send Content-Length headers or to enforce limits during file downloads.

Conclusion

The PHP filesize() function is a fundamental and straightforward way to determine file sizes in bytes. Whether you're validating uploads, logging file information, or monitoring system usage, it plays a critical role in PHP file system operations. Remember to handle errors carefully, check file existence, and optimize for performance when dealing with large scale or high-traffic applications. By mastering filesize() and understanding its nuances, you can greatly enhance the robustness and efficiency of your PHP applications.