Current Location: Home> Latest Articles> PHP filesize Function Tutorial: How to Get File Size and Application Scenarios

PHP filesize Function Tutorial: How to Get File Size and Application Scenarios

gitbox 2025-07-15

PHP filesize Function Usage and Application Analysis

In PHP programming, file operations are a common task. This article will thoroughly introduce the PHP filesize function to help developers better understand its functionality and use cases.

What is the filesize function?

The filesize function is a built-in PHP function used to get the size of a specified file. It returns the size of the file in bytes, and returns false if the file does not exist or an error occurs.

Basic Syntax of the filesize Function

The basic syntax of the filesize function is as follows:

filesize(string $filename): int|false

Here, $filename is the path of the file whose size is to be calculated.

Example of Using the filesize Function

Below is a simple example that uses the filesize function to get the file size:


$filename = 'example.txt';
if (file_exists($filename)) {
    $filesize = filesize($filename);
    echo "File size: " . $filesize . " bytes";
} else {
    echo "File does not exist.";
}

Handling Return Values

When using the filesize function, it's important to handle the return value properly. If the file does not exist or is inaccessible, the function will return false. Developers can use conditional checks to handle the error and ensure code robustness.

Application Scenarios of the filesize Function

The filesize function is widely used in practical development. Some common use cases include:

  • Limiting the size of uploaded files
  • Displaying basic file information (e.g., in a file management system)
  • Monitoring file storage usage

Example of Limiting Uploaded File Size

The following example shows how to validate the file size before uploading, ensuring the file meets the size requirements:


$uploadfile = $_FILES['userfile']['tmp_name'];
$maxfilesize = 2000000; // 2MB
if (filesize($uploadfile) > $maxfilesize) {
    echo "File exceeds maximum size limit.";
} else {
    echo "File uploaded successfully.";
}

Conclusion

The filesize function in PHP provides a convenient way for developers to get the size of a file. By using this function effectively, it can improve efficiency in file uploads and file management scenarios. Mastering the usage of the filesize function will not only enhance file operations but also help developers better handle errors.