在 PHP 中获取 POST 请求的大小

发布于 2024-08-04 08:03:05 字数 37 浏览 4 评论 0原文

有什么方法可以获取 PHP 中 POST 请求正文的大小吗?

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

许久 2024-08-11 08:03:05

简单如下:

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

请注意,仅当 HTTP 请求方法为 POST(而非 GET)时才会设置 $_SERVER['CONTENT_LENGTH']。这是 Content-Length 标头的原始值,如 RFC 7230

在文件上传的情况下,如果您想获取上传文件的总大小,您应该迭代 $_FILE 数组来对每个 $file[ '尺寸']。由于 POST 数据的编码开销,确切的总大小可能与原始 Content-Length 值不匹配。 (另请注意,您应该使用每个 $_FILES 元素的 $file['error'] 代码检查上传错误,例如 UPLOAD_ERR_PARTIAL部分上传或空上传的 UPLOAD_ERR_NO_FILE 请参阅 PHP 手册中的文件上传错误文档。)

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.)

菊凝晚露 2024-08-11 08:03:05

如果您想确定文件上传是否失败,您应该使用 PHP 文件错误处理,如下面的链接所示。这是检测文件上传错误的最可靠方法:
https://www.php.net/manual/en/ features.file-upload.errors.php

如果您需要 POST 请求的大小而无需上传任何文件,您应该可以使用如下方法来实现:

$request = http_build_query($_POST);
$size = strlen($request);

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:
https://www.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);
安静 2024-08-11 08:03:05

我的猜测是,它位于 $_SERVER['CONTENT_LENGTH'] 中。

如果您需要它来进行错误检测,请查看 $_FILES['filename']['error']

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

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

甜是你 2024-08-11 08:03:05

这可能有效:

$bytesInPostRequestBody = strlen(file_get_contents('php://input'));
// This does not count the bytes of the request's headers on its body.

This might work :

$bytesInPostRequestBody = strlen(file_get_contents('php://input'));
// This does not count the bytes of the request's headers on its body.
澉约 2024-08-11 08:03:05

我猜您正在寻找 $HTTP_RAW_POST_DATA

I guess you are looking for $HTTP_RAW_POST_DATA

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文