gpt4 book ai didi

php - 如何在 php 中获取 POST 的正文?

转载 作者:IT老高 更新时间:2023-10-28 11:39:07 25 4
gpt4 key购买 nike

我将以下内容作为 POST 提交到 php 页面:

{a:1}

这是请求的主体(POST 请求)。
在 php 中,我该怎么做才能提取该值?

var_dump($_POST); 

不是解决方案,不起作用。

最佳答案

访问 POST 或 PUT 请求(或任何其他 HTTP 方法)的实体主体:

$entityBody = file_get_contents('php://input');

另外,STDIN 常量是一个已经打开的 php://input 流,所以你也可以这样做:

$entityBody = stream_get_contents(STDIN);

来自 PHP manual entry on I/O streamsdocs :

php://input is a read-only stream that allows you to read raw data from the request body. In the case of POST requests, it is preferable to use php://input instead of $HTTP_RAW_POST_DATA as it does not depend on special php.ini directives. Moreover, for those cases where $HTTP_RAW_POST_DATA is not populated by default, it is a potentially less memory intensive alternative to activating always_populate_raw_post_data. php://input is not available with enctype="multipart/form-data".

您需要特别注意 php://input 流,无论您如何在 Web SAPI 中访问它,都是不可搜索的。这意味着它只能被读取一次。如果您在经常上传大型 HTTP 实体主体的环境中工作,您可能希望以流形式维护输入(而不是像上面的第一个示例那样缓冲它)。

为了维护流资源,这样的事情可能会有所帮助:

<?php

function detectRequestBody() {
$rawInput = fopen('php://input', 'r');
$tempStream = fopen('php://temp', 'r+');
stream_copy_to_stream($rawInput, $tempStream);
rewind($tempStream);

return $tempStream;
}

php://temp 允许您管理内存消耗,因为它会在存储一定数量的数据(默认为 2M)后透明地切换到文件系统存储。可以在 php.ini 文件中或通过附加 /maxmemory:NN 来操作此大小,其中 NN 是在使用临时文件之前要保留在内存中的最大数据量, 以字节为单位。

当然,除非您有充分的理由在输入流上进行搜索,否则您不应该在 Web 应用程序中需要此功能。读取 HTTP 请求实体正文一次通常就足够了——不要让客户端整天等待,而您的应用正在弄清楚该做什么。

请注意,php://input 不适用于指定 Content-Type: multipart/form-data header (enctype="multipart/form-data" 在 HTML 表单中)。这是因为 PHP 已经将表单数据解析为 $_POST 超全局变量。

关于php - 如何在 php 中获取 POST 的正文?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8945879/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com