IT이야기

PHP 실제 최대 업로드 크기 얻기

cyworld 2021. 4. 20. 21:42
반응형

PHP는 실제 최대 업로드 크기를 얻습니다.


사용할 때

ini_get("upload_max_filesize");

실제로 php.ini 파일에 지정된 문자열을 제공합니다.

이 값을 최대 업로드 크기에 대한 참조로 사용하는 것은 좋지 않습니다.

  • 소위 사용할 수 있습니다 shorthandbytes을 같이 1M하고 그렇게하는 추가 분석을 많이 필요
  • 예를 들어 upload_max_filesize가 0.25M이면 실제로는 ZERO이므로 값의 구문 분석을 다시 한 번 더 어렵게 만듭니다.
  • 또한 값에 공백이 포함되어 있으면 php에 의해 ZERO로 해석되고 사용할 때 공백이없는 값을 표시합니다. ini_get

그렇다면에서보고 한 것 외에 PHP에서 실제로 사용중인 값을 얻을 수있는 ini_get방법이 있습니까? 아니면이를 결정하는 가장 좋은 방법은 무엇입니까?


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);
  }
}

위의 기능은 Drupal 어디에서나 사용할 수 있으며 GPL 라이선스 버전 2 이상의 조건에 따라 복사하여 자신의 프로젝트에서 사용할 수 있습니다.

질문의 파트 2와 3의 경우 php.ini파일을 직접 구문 분석해야합니다 . 이것은 본질적으로 구성 오류이며 PHP는 대체 동작에 의존합니다. 실제로 php.iniPHP 에서로드 된 파일 의 위치를 ​​얻을 수있는 것처럼 보이지만 , 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;

여기에 완전한 솔루션이 있습니다. 속기 바이트 표기법과 같은 모든 트랩을 처리하고 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;
}      

다음은이 소스의 오류없는 버전입니다. http://www.smokycogs.com/blog/finding-the-maximum-file-upload-size-in-php/ .


이것이 내가 사용하는 것입니다.

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);
}

불가능한 것 같습니다.

이 때문에이 코드를 계속 사용할 것입니다.

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'));

원래부터 도움이 php.net 코멘트.

더 나은 답변을받을 수 있도록 열려 있습니다.


적어도 당신이 정의한 방식으로는 그렇게 생각하지 않습니다. 최대 파일 업로드 크기, 특히 사용자의 연결 속도, 웹 서버 및 PHP 프로세스의 시간 제한 설정을 고려하는 다른 많은 요소가 있습니다.

더 유용한 메트릭은 주어진 입력에 대해 수신 할 것으로 예상되는 파일 유형에 대해 적절한 최대 파일 크기를 결정하는 것입니다. 사용 사례에 적합한 것이 무엇인지 결정하고 이에 대한 정책을 설정하십시오.


이 구문을 사용하면 PHP ini 파일에서 정확한 숫자를 얻을 수 있습니다.

$maxUpload      = (int)(ini_get('upload_max_filesize'));
$maxPost        = (int)(ini_get('post_max_size'));

참조 URL : https://stackoverflow.com/questions/13076480/php-get-actual-maximum-upload-size

반응형