In the world of web development, understanding how to manage file sizes is a fundamental skill. Whether you’re dealing with user uploads, downloads, or simply displaying file information, knowing how to represent file sizes in a user-friendly manner is essential. After all, no one wants to decipher a string of bytes when they could see a more human-readable format.

In this post, we’ll delve into the realm of PHP programming to explore a simple yet effective way to get the friendly file size. By the end of this article, you’ll have the knowledge and tools to convert those raw file sizes into user-friendly formats that are both informative and easy to understand. Whether you’re building a file-sharing platform, managing media assets, or handling downloads, this PHP code will be a valuable addition to your toolkit.

Let’s embark on this journey to make file sizes more user-friendly and enhance the overall user experience on your web applications.

PHP Code

following code is very simple to get the friendly file size format using php code.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
function frndlyfilesize($filesize){

if(is_numeric($filesize)){
$decr = 1024;
$step = 0;
$prefix = array('Byte','KB','MB','GB','TB','PB');

while(($fileName / $decr) > 0.9){
$filesize = $filesize / $decr;
$step++;
}
return round($filesize,2).' '.$prefix[$step];
} else {

return 'Nothing';
}
}

 

To call that function :

1
2
$ filesize = filesize("test.jpg");
$newSize = frndlyfilesize($filesize);

 

Expected output like the format :

 

5 MB  or 5 KB or 5 GB ……

In the world of web development, the size of files matters. Whether you’re handling images, videos, documents, or any other type of file, striking the right balance between file size and quality is essential. In this article, we’ve delved into the PHP code that allows you to determine the optimal file size for your specific use case. By implementing these techniques, you can ensure that your web application provides a smooth and efficient experience for users while maintaining the quality of your files. Finding the “friendly” file size is a crucial step in optimizing your website’s performance and enhancing user satisfaction.


1 Comment

Ruel · January 12, 2011 at 5:17 pm

I think it should be
while(($filesize / $decr) > 0.9)

and NOT
while(($fileName / $decr) > 0.9)

Leave a Reply

Avatar placeholder

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