Drupal has this implemented fairly elegantly:
// Returns a file size limit in bytes based on the PHP upload_max_filesize
// and post_max_size
function file_upload_max_size() {
static $max_size = -1;
if ($max_size < 0) {
// Start with post_max_size.
$post_max_size = parse_size(ini_get('post_max_size'));
if ($post_max_size > 0) {
$max_size = $post_max_size;
}
// If upload_max_size is less, then reduce. Except if upload_max_size is
// zero, which indicates no limit.
$upload_max = parse_size(ini_get('upload_max_filesize'));
if ($upload_max > 0 && $upload_max < $max_size) {
$max_size = $upload_max;
}
}
return $max_size;
}
function parse_size($size) {
$unit = preg_replace('/[^bkmgtpezy]/i', '', $size); // Remove the non-unit characters from the size.
$size = preg_replace('/[^0-9\.]/', '', $size); // Remove the non-numeric characters from the size.
if ($unit) {
// Find the position of the unit in the ordered string which is the power of magnitude to multiply a kilobyte by.
return round($size * pow(1024, stripos('bkmgtpezy', $unit[0])));
}
else {
return round($size);
}
}
The above functions are available anywhere in Drupal, or you can copy it and use it in your own project subject to the terms of the GPL license version 2 or later.
As for parts 2 and 3 of your question, you will need to parse the php.ini
file directly. These are essentially configuration errors, and PHP is resorting to fallback behaviors. It appears you can actually get the location of the loaded php.ini
file in PHP, although trying to read from it may not work with basedir or safe-mode enabled:
$max_size = -1;
$files = array_merge(array(php_ini_loaded_file()), explode(",
", php_ini_scanned_files()));
foreach (array_filter($files) as $file) {
$ini = parse_ini_file($file);
$regex = '/^([0-9]+)([bkmgtpezy])$/i';
if (!empty($ini['post_max_size']) && preg_match($regex, $ini['post_max_size'], $match)) {
$post_max_size = round($match[1] * pow(1024, stripos('bkmgtpezy', strtolower($match[2])));
if ($post_max_size > 0) {
$max_size = $post_max_size;
}
}
if (!empty($ini['upload_max_filesize']) && preg_match($regex, $ini['upload_max_filesize'], $match)) {
$upload_max_filesize = round($match[1] * pow(1024, stripos('bkmgtpezy', strtolower($match[2])));
if ($upload_max_filesize > 0 && ($max_size <= 0 || $max_size > $upload_max_filesize) {
$max_size = $upload_max_filesize;
}
}
}
echo $max_size;