我提交POST到一个php页面如下:

{a:1}

这是请求的主体(POST请求)。 在php中,我需要做什么来提取这个值?

var_dump($_POST); 

不是解决办法,行不通。


当前回答

在数组中返回值

 $data = json_decode(file_get_contents('php://input'), true);

其他回答

检查$HTTP_RAW_POST_DATA变量

http_get_request_body()根据文档http://php.net/manual/fa/function.http-get-request-body.php显式地用于获取PUT和POST请求的主体

一个空$_POST的可能原因是请求不是POST,或者不再POST了…它可能开始是post,但在某处遇到301或302重定向,这被切换到GET!

检查$_SERVER['REQUEST_METHOD']以检查是否是这种情况。

有关为什么这种情况不应该发生,但仍然发生的良好讨论,请参阅https://stackoverflow.com/a/19422232/109787。

如果您已经安装了HTTP PECL扩展,您可以使用http_get_request_body()函数以字符串形式获取主体数据。

function getPost()
{
    if(!empty($_POST))
    {
        // when using application/x-www-form-urlencoded or multipart/form-data as the HTTP Content-Type in the request
        // NOTE: if this is the case and $_POST is empty, check the variables_order in php.ini! - it must contain the letter P
        return $_POST;
    }

    // when using application/json as the HTTP Content-Type in the request 
    $post = json_decode(file_get_contents('php://input'), true);
    if(json_last_error() == JSON_ERROR_NONE)
    {
        return $post;
    }

    return [];
}

print_r(getPost());