Get size of POST-request in PHP

后端 未结 5 2044
遥遥无期
遥遥无期 2020-11-28 15:55

Is there any way to get size of POST-request body in PHP?

相关标签:
5条回答
  • 2020-11-28 16:09

    As simple as:

    $size = (int) $_SERVER['CONTENT_LENGTH'];
    

    Note that $_SERVER['CONTENT_LENGTH'] is only set when the HTTP request method is POST (not GET). This is the raw value of the Content-Length header, as specified in RFC 7230.

    In the case of file uploads, if you want to get the total size of uploaded files, you should iterate over the $_FILE array to sum each $file['size']. The exact total size might not match the raw Content-Length value due to the encoding overhead of the POST data. (Also note you should check for upload errors using the $file['error'] code of each $_FILES element, such as UPLOAD_ERR_PARTIAL for partial uploads or UPLOAD_ERR_NO_FILE for empty uploads. See file upload errors documentation in the PHP manual.)

    0 讨论(0)
  • 2020-11-28 16:17

    This might work :

    $bytesInPostRequestBody = strlen(file_get_contents('php://input'));
    // This does not count the bytes of the request's headers on its body.
    
    0 讨论(0)
  • 2020-11-28 16:28

    My guess is, it's in the $_SERVER['CONTENT_LENGTH'].

    And if you need that for error detection, peek into $_FILES['filename']['error'].

    0 讨论(0)
  • 2020-11-28 16:31

    I guess you are looking for $HTTP_RAW_POST_DATA

    0 讨论(0)
  • 2020-11-28 16:33

    If you're trying to figure out whether or not a file upload failed, you should be using the PHP file error handling as shown at the link below. This is the most reliable way to detect file upload errors:
    http://us3.php.net/manual/en/features.file-upload.errors.php

    If you need the size of a POST request without any file uploads, you should be able to do so with something like this:

    $request = http_build_query($_POST);
    $size = strlen($request);
    
    0 讨论(0)
提交回复
热议问题