PHP Filesize with Program Example

In this tutorial, we will discuss how to get the file size using PHP. To get the file size we will need the file size function. Also, we will know what is the meaning of filesize() function, the parameter used and the syntax description.

What is PHP filesize?

The filesize function returns the file size in bites and it will accept the filename as a parameter by returning the file size into bytes with success and failure.

How do you find the file size?

Choose a file then right click and then click properties. It will show the type, and location of a file you choose, the size of mb for megabytes, and kb for kilobytes, the size in disk, contains, created and the attributes.

The Error or Exceptions

If it is failure, it will show result E_Warning.

Syntax Description

filesize($my_file_name)

The Parameters Used

The filename parameter will require the specific path of the file you want to check.

Example of PHP file size function

<?php


    
echo "File size: ";
echo filesize("phpFilesize.txt");
  
?>

Output:
File Size: 79

Other Example

You can also format the unit of the size with this function for kilobytes

$my_file = '/path/to/your/file';
$my_file_size = filesize($my_file ); // bytes
$my_file_size = round($my_file_size / 1024, 2); // kilobytes with two digits
 
echo "The size of your file is $my_file_size KB.";

You can also format the unit of the size with this function for megabytes.

$my_file = '/path/to/your/file';
$my_file_size = filesize($my_file ); // bytes
$my_file_size = round($my_file_size / 1024 / 1024, 1); // megabytes with 1 digit
 
echo "The size of your file is $my_file_size MB.";

Reminder: The results of this function will be cached. We will use clearstatcache() to clear the cache information.

Conclusion

In conclusion, we discussed how to get the file size in PHP and we already provide the example and output by getting the file size such as kilobytes and megabytes.

Leave a Comment