How to check the size of a file in PHP

PHP-IconPHP has a handy function called filesize() which can help us display how big a file is.

It does this in bytes by default, but with a bit of tinkering we can easily convert this into kilobytes or megabytes.

Let’s first see how this works in bytes:

Converting bytes into kilobytes works by dividing the value by 1024. PHP is very accurate and will give you 12 decimal digits – perhaps a little overkill. To avoid this we can make use of the round() function and specify how many digits of accuracy we’d like to display:

To display the value in megabytes we’ll simply divide by 1024 twice:

  • http://www.php.net/manual/en/function.filesize.php
  • http://us3.php.net/round

Jay is the CEO and founder of WP Hosting, a boutique style managed WordPress hosting and support service. He has been working with Plesk since version 9 and is a qualified Parallels Automation Professional. In his spare time he likes to develop iOS apps and WordPress plugins, or draw on tablet devices. He blogs about his coding journey at http://wpguru.co.uk and http://pinkstone.co.uk.

One thought on “How to check the size of a file in PHP

Add your voice!