我作为POST提交到php页面如下:
{a:1}
Run Code Online (Sandbox Code Playgroud)
这是请求的主体(POST请求).
在php中,我需要做些什么才能提取该值?
var_dump($_POST);
Run Code Online (Sandbox Code Playgroud)
不是解决方案,不起作用.
rdl*_*rey 507
要访问POST或PUT请求(或任何其他HTTP方法)的实体主体:
$entityBody = file_get_contents('php://input');
Run Code Online (Sandbox Code Playgroud)
此外,STDIN常量是一个已打开的流php://input,因此您可以选择:
$entityBody = stream_get_contents(STDIN);
Run Code Online (Sandbox Code Playgroud)
php:// input是一个只读流,允许您从请求正文中读取原始数据.在POST请求的情况下,最好使用php:// input而不是
$HTTP_RAW_POST_DATA因为它不依赖于特殊的php.ini指令.此外,对于$HTTP_RAW_POST_DATA默认情况下 未填充的情况,它可能是激活always_populate_raw_post_data的内存密集型替代方案.php://输入不适用于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;
}
Run Code Online (Sandbox Code Playgroud)
php://temp允许您管理内存消耗,因为它会在存储一定数量的数据后透明地切换到文件系统存储(默认为2M).这个大小可以在php.ini文件中操作,也可以通过附加/maxmemory:NN,NN在使用临时文件之前保存在内存中的最大数据量(以字节为单位).
当然,除非您有充分的理由在输入流上进行搜索,否则您不应该在Web应用程序中使用此功能.一次读取HTTP请求实体主体通常就足够了 - 当您的应用程序弄清楚要做什么时,不要让客户整天等待.
请注意,php://输入不适用于指定Content-Type: multipart/form-data标题的请求(enctype="multipart/form-data"在HTML表单中).这是因为PHP已经将表单数据解析为$_POST超全局.
Leg*_*las 11
空的一个可能原因$_POST是请求不是POST,或者POST不再...它可能已经开始作为帖子,但遇到了某个地方301或302重定向,切换到GET!
检查$_SERVER['REQUEST_METHOD']是否是这种情况.
请参阅/sf/answers/1359556271/,以便更好地讨论为什么不应该这样做,但仍然可以.
Vin*_*nci 11
这是如何创建 php api 并在using withfile_get_contents("php://input")中使用的示例。javascriptajaxXMLHttpRequest
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState == 4 && this.status == 200) {
console.log("done");
}
}
};
xhttp.open("POST", "http://127.0.0.1:8000/api.php", true);
xhttp.send(JSON.stringify({
username: $(this).val(),
email:email,
password:password
}));
Run Code Online (Sandbox Code Playgroud)
$data = json_decode(file_get_contents("php://input"));
$username = $data->username;
$email = $data->email;
$password = $data->password;
Run Code Online (Sandbox Code Playgroud)
小智 6
返回数组中的值
$data = json_decode(file_get_contents('php://input'), true);
Run Code Online (Sandbox Code Playgroud)
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());
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
234868 次 |
| 最近记录: |