Programing

PHP의`post_max_size`를 초과하는 파일을 정상적으로 처리하는 방법은 무엇입니까?

lottogame 2020. 9. 25. 08:12
반응형

PHP의`post_max_size`를 초과하는 파일을 정상적으로 처리하는 방법은 무엇입니까?


이메일에 파일을 첨부하는 PHP 양식을 작업 중이며 업로드 된 파일이 너무 큰 경우를 정상적으로 처리하려고합니다.

나는 두 설정이 있다는 것을 배웠다 php.ini즉 파일 업로드의 maxiumum 크기에 영향을 upload_max_filesize하고 post_max_size.

파일 크기가를 초과 upload_max_filesize하면 PHP는 파일 크기를 0으로 반환합니다. 괜찮습니다. 확인할 수 있습니다.

그러나을 초과하면 post_max_size스크립트가 자동으로 실패하고 빈 양식으로 돌아갑니다.

이 오류를 잡을 방법이 있습니까?


에서 문서 :

게시 데이터의 크기가 post_max_size보다 크면 $ _POST 및 $ _FILES 수퍼 글로벌이 비어 있습니다. 이는 다양한 방법으로 추적 할 수 있습니다. 예를 들어 데이터를 처리하는 스크립트에 $ _GET 변수 (예 : <form action = "edit.php? processed = 1">)를 전달한 다음 $ _GET [ 'processed']가 세트.

불행히도 PHP가 오류를 보내는 것처럼 보이지 않습니다. 그리고 빈 $ _POST 배열을 보내기 때문에 스크립트가 빈 양식으로 돌아가는 이유입니다. POST라고 생각하지 않습니다. (아주 좋지 않은 디자인 결정 IMHO)

이 댓글 작성자 도 흥미로운 아이디어를 가지고 있습니다.

보다 우아한 방법은 post_max_size와 $ _SERVER [ 'CONTENT_LENGTH']를 비교하는 것 같습니다. 후자는 업로드 된 파일의 크기와 포스트 데이터뿐만 아니라 멀티 파트 시퀀스도 포함합니다.


최대 게시물 크기를 초과하는 파일을 포착 / 처리하는 방법이 있습니다. 이것은 최종 사용자에게 무슨 일이 있었는지 그리고 누가 잘못했는지 알려주기 때문에 제가 선호하는 것입니다.)

if (empty($_FILES) && empty($_POST) &&
        isset($_SERVER['REQUEST_METHOD']) &&
        strtolower($_SERVER['REQUEST_METHOD']) == 'post') {
    //catch file overload error...
    $postMax = ini_get('post_max_size'); //grab the size limits...
    echo "<p style=\"color: #F00;\">\nPlease note files larger than {$postMax} will result in this error!<br>Please be advised this is not a limitation in the CMS, This is a limitation of the hosting server.<br>For various reasons they limit the max size of uploaded files, if you have access to the php ini file you can fix this by changing the post_max_size setting.<br> If you can't then please ask your host to increase the size limits, or use the FTP uploaded form</p>"; // echo out error and solutions...
    addForm(); //bounce back to the just filled out form.
}
else {
    // continue on with processing of the page...
}

$ _POST 및 $ _FILES의 비어 있는지 확인이 작동하지 않는 SOAP 요청에 대한 문제가 있습니다. 유효한 요청에서도 비어 있기 때문입니다.

따라서 CONTENT_LENGTH와 post_max_size를 비교하는 검사를 구현했습니다. 던져진 예외는 나중에 등록 된 예외 핸들러에 의해 XML-SOAP-FAULT로 변환됩니다.

private function checkPostSizeExceeded() {
    $maxPostSize = $this->iniGetBytes('post_max_size');

    if ($_SERVER['CONTENT_LENGTH'] > $maxPostSize) {
        throw new Exception(
            sprintf('Max post size exceeded! Got %s bytes, but limit is %s bytes.',
                $_SERVER['CONTENT_LENGTH'],
                $maxPostSize
            )
        );
    }
}

private function iniGetBytes($val)
{
    $val = trim(ini_get($val));
    if ($val != '') {
        $last = strtolower(
            $val{strlen($val) - 1}
        );
    } else {
        $last = '';
    }
    switch ($last) {
        // The 'G' modifier is available since PHP 5.1.0
        case 'g':
            $val *= 1024;
            // fall through
        case 'm':
            $val *= 1024;
            // fall through
        case 'k':
            $val *= 1024;
            // fall through
    }

    return $val;
}

Building on @Matt McCormick's and @AbdullahAJM's answers, here is a PHP test case that checks the variables used in the test are set and then checks if the $_SERVER['CONTENT_LENGTH'] exceeds the php_max_filesize setting:

            if (
                isset( $_SERVER['REQUEST_METHOD'] )      &&
                ($_SERVER['REQUEST_METHOD'] === 'POST' ) &&
                isset( $_SERVER['CONTENT_LENGTH'] )      &&
                ( empty( $_POST ) )
            ) {
                $max_post_size = ini_get('post_max_size');
                $content_length = $_SERVER['CONTENT_LENGTH'] / 1024 / 1024;
                if ($content_length > $max_post_size ) {
                    print "<div class='updated fade'>" .
                        sprintf(
                            __('It appears you tried to upload %d MiB of data but the PHP post_max_size is %d MiB.', 'csa-slplus'),
                            $content_length,
                            $max_post_size
                        ) .
                        '<br/>' .
                        __( 'Try increasing the post_max_size setting in your php.ini file.' , 'csa-slplus' ) .
                        '</div>';
                }
            }

That is a simple way to fix this problem:

Just call "checkPostSizeExceeded" on begin of your code

function checkPostSizeExceeded() {
        if (isset($_SERVER['REQUEST_METHOD']) and $_SERVER['REQUEST_METHOD'] == 'POST' and
            isset($_SERVER['CONTENT_LENGTH']) and empty($_POST)//if is a post request and $_POST variable is empty(a symptom of "post max size error")
        ) {
            $max = get_ini_bytes('post_max_size');//get the limit of post size 
            $send = $_SERVER['CONTENT_LENGTH'];//get the sent post size

            if($max < $_SERVER['CONTENT_LENGTH'])//compare
                throw new Exception(
                    'Max size exceeded! Were sent ' . 
                        number_format($send/(1024*1024), 2) . 'MB, but ' . number_format($max/(1024*1024), 2) . 'MB is the application limit.'
                    );
        }
    }

Remember copy this auxiliar function:

function get_ini_bytes($attr){
    $attr_value = trim(ini_get($attr));

    if ($attr_value != '') {
        $type_byte = strtolower(
            $attr_value{strlen($attr_value) - 1}
        );
    } else
        return $attr_value;

    switch ($type_byte) {
        case 'g': $attr_value *= 1024*1024*1024; break;
        case 'm': $attr_value *= 1024*1024; break;
        case 'k': $attr_value *= 1024; break;
    }

    return $attr_value;
}

참고URL : https://stackoverflow.com/questions/2133652/how-to-gracefully-handle-files-that-exceed-phps-post-max-size

반응형