2011-07-27 60 views
12

當從ini_get('upload_max_filesize')ini_get('post_max_size')使用shorthand byte notation時,有沒有什麼辦法從函數返回的字符串中獲取字節值?例如從4M獲得4194304?我可以一起攻擊一個這樣做的函數,但如果沒有這樣做的話,我會感到驚訝。從php.ini中的簡寫字節表示法獲取字節值

+2

如果從您發佈的鏈接閱讀,PHP的文檔告訴你怎麼做... –

+0

也請參見http://計算器.com/q/1336581/632951 – Pacerier

回答

20

The paragraph you linked to結束:

你可能不使用這些符號php.ini之外,代替 使用字節的整數值。 有關如何轉換這些值的 示例,請參閱the ini_get() documentation

這導致你這樣的事情(我稍微修改):

function return_bytes($val) 
{ 
    $val = trim($val); 

    $last = strtolower($val[strlen($val)-1]); 
    $val = substr($val, 0, -1); // necessary since PHP 7.1; otherwise optional 

    switch($last) { 
     // The 'G' modifier is available since PHP 5.1.0 
     case 'g': 
      $val *= 1024; 
     case 'm': 
      $val *= 1024; 
     case 'k': 
      $val *= 1024; 
    } 

    return $val; 
} 

使用它like so

echo return_bytes("3M"); 
// Output: 3145728 

有執行此沒有內置功能任務;回想一下,實際上,INI設置旨在在PHP內部使用內部。 PHP源代碼使用與上述類似的功能。

+2

剛剛看到 - 有一些免費的代表! –

+0

cool switch +1真的很喜歡這個概念 –

+1

在7.1中要小心,在乘法之前你需要從修飾符中分離數值 $ val = substr($ val,0,-1); – Bouffe

2

嘎!剛剛發現的http://www.php.net/manual/en/function.ini-get.php

只需要RTM答案...

function return_bytes($val) { 
    $val = trim($val); 
    $last = strtolower($val[strlen($val)-1]); 
    switch($last) { 
     // The 'G' modifier is available since PHP 5.1.0 
     case 'g': 
      $val *= 1024; 
     case 'm': 
      $val *= 1024; 
     case 'k': 
      $val *= 1024; 
    } 

    return $val; 
} 
-1

這是一種方式。

$str=ini_get('upload_max_filesize'); 
preg_match('/[0-9]+/', $str, $match); 

echo ($match[0] * 1024 * 1024); // <--This is MB converted to bytes 
+0

如果該值不是兆字節,該怎麼辦? –

+0

然後上面的代碼將不得不針對不同的轉換進行調整。大多數php.ini中的設置都使用MB,包括上面提到的示例。 – Tanoro

+0

所以這個答案是不完整的。 –

0

我發現了很多解決方案來解決這個問題,應該有一個內置函數來解決這個問題。在任何情況下,兩件事情要突出這個問題:

  1. 這是非常具體的PHP的縮寫的字節值如下解釋:http://php.net/manual/en/faq.using.php#faq.using.shorthandbytes,只應在這個上下文中使用。
  2. 大多數現代IDE將發出警告switch陳述沒有break

這裏是一個涵蓋了一個解決方案:

/** 
* Convert PHP's directive values to bytes (including the shorthand syntax). 
* 
* @param string $directive The PHP directive from which to get the value from. 
* 
* @return false|int Returns the value of the directive in bytes if available, otherwise false. 
*/ 
function php_directive_value_to_bytes($directive) { 
    $value = ini_get($directive); 

    // Value must be a string. 
    if (!is_string($value)) { 
     return false; 
    } 

    preg_match('/^(?<value>\d+)(?<option>[K|M|G]*)$/i', $value, $matches); 

    $value = (int) $matches['value']; 
    $option = strtoupper($matches['option']); 

    if ($option) { 
     if ($option === 'K') { 
      $value *= 1024; 
     } elseif ($option === 'M') { 
      $value *= 1024 * 1024; 
     } elseif ($option === 'G') { 
      $value *= 1024 * 1024 * 1024; 
     } 
    } 

    return $value; 
}