PHP & MySQL | Tutorials

David Carr

Simpler filesize calculations

When working with file sizes in PHP you work with bytes, which often is not what you want. In most cases I prefer to work with megabytes rather the bytes, I came across a snippet on Stackoverflow that solved this issue in a great way.

First, define the different sizes:

define('KB', 1024);
define('MB', 1048576);
define('GB', 1073741824);
define('TB', 1099511627776);

Then you can use them in if statements calculations ie to only allow images less than 20MB:

if ($size < 20*MB) {

Super handy!

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2020 DC Blog. All code MIT license. All rights reserved.