How to find file size in PHP

How to find file size in PHP

Colleagues hello to all.

In today's article, we'll talk about how to find out the size of a file in PHP.

Sooner or later in your applications you will be faced with the task of knowing the size of a file. There are a lot of examples why we need to know the size of files, and one of the examples could be when you or a user starts uploading images or some file to your server, and before you start uploading this file, you can include conditions for checking by the maximum size uploaded file.

In PHP, there are two options for how to view the size of a file, and we'll look at them today. 

 

In the first variant, we will use the filesize function. The filesize function takes only one required parameter, the file name. The function returns the size of the file in bytes. In the event of an error, it returns FALSE and generates an E_WARNING level error.

php> filesize('it-inzhener.png');

php file size

In this example, we get the size of the it-inzhener.png image, and the result is 105478 bytes.

Getting the file size in bytes is very inconvenient, and therefore we can make a function that will convert bytes to other values ​​for us.

function getFilesize($filesize)
{
    if ($filesize > 1024) {
        $filesize = ($filesize / 1024);
        if ($filesize > 1024) {
            $filesize = ($filesize / 1024);
            if ($filesize > 1024) {
                $filesize = ($filesize / 1024);
                $filesize = round($filesize, 1);
                return $filesize . " GB";
            } else {
                $filesize = round($filesize, 1);
                return $filesize . " MB";
            }
        } else {
            $filesize = round($filesize, 1);
            return $filesize . " KB";
        }
    } else {
        $filesize = round($filesize, 1);
        return $filesize . " bytes";
    }
}

The function takes the size in bytes, and returns the size in other values. The function converts bytes to the desired value, based on the size of the file itself.

php file size


 

The next option to get the file size is to use a special php class called SplFileInfo. First, we need to create an object of this class and pass the file itself to its constructor, then we need to execute the method of this class called getSize. The getSize method returns the size of the file, also in bytes, and in case of any error it will return FALSE.

$splFile = new SplFileInfo('it-inzhener.png');
echo $splFile->getSize();

php file size


 

Thank you all, I hope that my article helped you in some way.

 

SIMILAR ARTICLES

HTML/CSS - Search Bar Without JavaScript
HTML/CSS - Search Bar Without JavaScript
WEB
Read more
HTML/CSS - Search Bar
HTML/CSS - Search Bar
WEB
Read more
Pure HTML/CSS search bar
Pure HTML/CSS search bar
WEB
Read more