Last active
August 29, 2015 13:57
-
-
Save Chengings/9597366 to your computer and use it in GitHub Desktop.
Convert number with unit byte to bytes unit & get maximum file upload size of php
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
/** | |
* Convert number with unit byte to bytes unit | |
* @link https://en.wikipedia.org/wiki/Metric_prefix | |
* @param string $value a number of bytes with optinal SI decimal prefix (e.g. 7k, 5mb, 3GB or 1 Tb) | |
* @return integer|float A number representation of the size in BYTES (can be 0). otherwise FALSE | |
*/ | |
function str2bytes($value) { | |
// only string | |
$unit_byte = preg_replace('/[^a-zA-Z]/', '', $value); | |
$unit_byte = strtolower($unit_byte); | |
// only number (allow decimal point) | |
$num_val = preg_replace('/\D\.\D/', '', $value); | |
switch ($unit_byte) { | |
case 'p': // petabyte | |
case 'pb': | |
$num_val *= 1024; | |
case 't': // terabyte | |
case 'tb': | |
$num_val *= 1024; | |
case 'g': // gigabyte | |
case 'gb': | |
$num_val *= 1024; | |
case 'm': // megabyte | |
case 'mb': | |
$num_val *= 1024; | |
case 'k': // kilobyte | |
case 'kb': | |
$num_val *= 1024; | |
case 'b': // byte | |
return $num_val *= 1; | |
break; // make sure | |
default: | |
return FALSE; | |
} | |
return FALSE; | |
} | |
/** | |
* The maximum file upload size by getting PHP settings | |
* @return integer|float file size limit in BYTES based | |
*/ | |
function maximum_upload_size() { | |
static $upload_size = NULL; | |
if ($upload_size === NULL) { | |
$post_max_size = str2bytes( ini_get('post_max_size') ); | |
$upload_max_filesize = str2bytes( ini_get('upload_max_filesize') ); | |
$memory_limit = str2bytes( ini_get('memory_limit') ); | |
// Even though we disable all of variables in php.ini. These still use default value | |
// Nearly impossible but check for sure | |
if (empty($post_max_size) && empty($upload_max_filesize) && empty($memory_limit)) { | |
return FALSE; | |
} | |
$upload_size = min($post_max_size, $upload_max_filesize, $memory_limit); | |
} | |
return $upload_size; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment