PHP获得实际的最大上传大小

Zul*_*kis 52 php

使用时

ini_get("upload_max_filesize");
Run Code Online (Sandbox Code Playgroud)

它实际上为您提供了php.ini文件中指定的字符串.

将此值用作最大上载大小的参考是不好的,因为

  • 也可以使用所谓的shorthandbytes1M等,这些需要大量的额外解析
  • 例如0.25M,当upload_max_filesize是,它实际上是ZERO,使得再次更难解析值
  • 另外,如果值包含任何空格,例如它被php解释为ZERO,而它在使用时显示没有空格的值 ini_get

那么,有没有办法让PHP实际使用的值,除了报告的ini_get那个,或者确定它的最佳方法是什么?

meu*_*rus 49

Drupal相当优雅地实现了这个:

// 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);
  }
}
Run Code Online (Sandbox Code Playgroud)

以上功能可在Drupal的任何位置使用,或者您可以根据GPL许可证版本2或更高版本的条款将其复制并在您自己的项目中使用.

至于问题的第2部分和第3部分,您需要php.ini直接解析文件.这些本质上是配置错误,PHP正在采用回退行为.看起来你实际上可以php.ini在PHP中获取加载文件的位置,尽管尝试从中读取它可能不适用于basedir或启用安全模式:

$max_size = -1;
$files = array_merge(array(php_ini_loaded_file()), explode(",\n", 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;
Run Code Online (Sandbox Code Playgroud)

  • `pow`系列非常优雅,但这只能解决问题中列出的3个问题之一. (3认同)

Car*_*itz 36

这是完整的解决方案.它处理所有陷阱,如速记字节表示法,并考虑post_max_size:

/**
* This function returns the maximum files size that can be uploaded 
* in PHP
* @returns int File size in bytes
**/
function getMaximumFileUploadSize()  
{  
    return min(convertPHPSizeToBytes(ini_get('post_max_size')), convertPHPSizeToBytes(ini_get('upload_max_filesize')));  
}  

/**
* This function transforms the php.ini notation for numbers (like '2M') to an integer (2*1024*1024 in this case)
* 
* @param string $sSize
* @return integer The value in bytes
*/
function convertPHPSizeToBytes($sSize)
{
    //
    $sSuffix = strtoupper(substr($sSize, -1));
    if (!in_array($sSuffix,array('P','T','G','M','K'))){
        return (int)$sSize;  
    } 
    $iValue = substr($sSize, 0, -1);
    switch ($sSuffix) {
        case 'P':
            $iValue *= 1024;
            // Fallthrough intended
        case 'T':
            $iValue *= 1024;
            // Fallthrough intended
        case 'G':
            $iValue *= 1024;
            // Fallthrough intended
        case 'M':
            $iValue *= 1024;
            // Fallthrough intended
        case 'K':
            $iValue *= 1024;
            break;
    }
    return (int)$iValue;
}      
Run Code Online (Sandbox Code Playgroud)

这是此源的无错误版本:http://www.smokycogs.com/blog/finding-the-maximum-file-upload-size-in-php/.

  • 在我最终意识到switch语句中只有一个"break"语句,并且"case"行的顺序很重要之前,我根本不知道它是如何工作的(特别是switch语句).它工作得很好,但我担心一些初级程序员会回来并试图稍后修改这段代码.也许"更标准化"的版本是更好的长期解决方案? (7认同)
  • @GavinG 我现在已经根据 PSR-2 的要求添加了适当的注释,因此失败是显而易见的。 (2认同)

jca*_*ll1 6

这是我使用的:

function asBytes($ini_v) {
   $ini_v = trim($ini_v);
   $s = [ 'g'=> 1<<30, 'm' => 1<<20, 'k' => 1<<10 ];
   return intval($ini_v) * ($s[strtolower(substr($ini_v,-1))] ?: 1);
}
Run Code Online (Sandbox Code Playgroud)

  • 2020 年我们可以使用 kbs &lt;?php function kbs($v){ return intval($v) * ([ 'p'=&gt; 1&lt;&lt;40, 't' =&gt; 1&lt;&lt;30, 'g'=&gt; 1&lt;&lt;20, 'm' =&gt; 1&lt;&lt;10, 'k' =&gt; 1 ][strtolower(substr(trim($v),-1))] ?: 1); } 回声(kbs('1g')); ?&gt; (3认同)

Zul*_*kis 5

看起来不可能.

因此,我将继续使用此代码:

function convertBytes( $value ) {
    if ( is_numeric( $value ) ) {
        return $value;
    } else {
        $value_length = strlen($value);
        $qty = substr( $value, 0, $value_length - 1 );
        $unit = strtolower( substr( $value, $value_length - 1 ) );
        switch ( $unit ) {
            case 'k':
                $qty *= 1024;
                break;
            case 'm':
                $qty *= 1048576;
                break;
            case 'g':
                $qty *= 1073741824;
                break;
        }
        return $qty;
    }
}
$maxFileSize = convertBytes(ini_get('upload_max_filesize'));
Run Code Online (Sandbox Code Playgroud)

最初来自这个有用的php.net评论.

仍然开放接受更好的答案