Skip to content

Instantly share code, notes, and snippets.

@og-shawn-crigger
Created April 9, 2012 13:59
Show Gist options
  • Save og-shawn-crigger/2343619 to your computer and use it in GitHub Desktop.
Save og-shawn-crigger/2343619 to your computer and use it in GitHub Desktop.
Get Max Upload Size from PHP ini's 'post_max_size' && 'upload_max_filesize'
<?php
//Simple Function to Get Max Upload Size from PHP
$max_upload = min(ini_get('post_max_size'), ini_get('upload_max_filesize'));
$max_upload = str_replace('M', '', $max_upload);
$max_upload = $max_upload * 1024;
@teroyks
Copy link

teroyks commented May 14, 2020

Hi,
This doesn't work unless the ini values have the same amount of digits, because min does a string comparison.
For example, min('10M', '2M') == '10M'

This fixes the issue (and doesn't need str_replace because the int conversion already does that):

$max_upload = min((int)ini_get('post_max_size'), (int)ini_get('upload_max_filesize'));
$max_upload = $max_upload * 1024;

@neilbannet
Copy link

+1 Thanks mate!

@jonathanbell
Copy link

This only accounts for values set in megabytes (M). I believe that these values can be set in K (kilobytes) and even G (gigabytes) with decimals.

@teroyks
Copy link

teroyks commented Sep 20, 2021

That’s true, although a bit more rare.

If you need to account for those as well, you could use something like this to convert the value:

function human_readable_to_bytes(string $amount): int {
    $units = ['', 'K', 'M', 'G'];
    
    preg_match('/(\d+)\s?([KMG]?)/', $amount, $matches);
    [$_, $nr, $unit] = $matches;
    $exp = array_search($unit, $units);
    return (int)$nr * pow(1024, $exp);
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment