Black Friday sale is now on! 50% off Laravel: The Modular Way. Learn more

Simpler filesize calculations

David Carr

PHP & MySQL Tutorials

    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!

    Laravel Modules Book by David Carr

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

    Subscribe to my newsletter

    Subscribe and get my books and product announcements.

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