How to get file size in PHP?

In this post I explain of how to get file size in PHP. You can understand a concept of get image size in PHP. This post will give you simple and easy to understand example of check image size in php. 

The filesize() function returns the size of a file in bytes. This function accepts the filename as a parameter and returns the file size of a file. It is a built-in function that returns the file size as an integer.

Syntax:
filesize($filename)

Parameters: The filesize() function in PHP accepts only one parameters. Example of $filename that specifies the filename of the file.

Example 1: How to get file size in php using filesize() function

In PHP,  you can get file size of a file using the filesize() function. We will explain simple example below. 

<?php

    $basefile = 'path of file here';
    $baseFileSize = filesize($basefile);
    
    echo "The size of file is: " .$baseFileSize . "bytes"; 
?>

In this example, the filesize() function is used to get the size of the file at the specified path. The size stored in the $baseFileSize variable, and printed to the echo statement.

Example 2: Get file size such as kilobytes and megabytes using filesize() function

The filesize() function returns the size of the file in bytes. If you want to display the size in a more format such as kilobytes and megabytes, you can use some additional code to convert the output.

<?php

    $basefile = 'path of file here';
    $baseFileSize = round($basefile / 1024 / 1024, 2) . 'MB';
    
    echo "The size of the file is: " .$baseFileSize; 
?>

In this example, the filesize() function is called as before, but the output is then divided by 1024 twice to convert it from bytes to megabytes. The round() function is used to round the output to two decimal places, and the output concatenated with string with ‘MB’ to create a readable format.

I hope this tutorial help you.

Leave a Reply

Your email address will not be published. Required fields are marked *