Hi, my name is David Carr and I'm a PHP Developer.


Blog Archives Categories Authors About Me Open Source Books Contact Me

Sponsor Me

Help support the blog so that I can continue creating new content!

My Latest Book

Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Simpler filesize calculations

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!

Copyright © 2009 - 2022 David Carr. All code MIT license. All rights reserved.