简体   繁体   English

清空没有Content-type的$ _POST

[英]Empty $_POST without Content-type

If I make a POST request where the content-type is not set in the request header, the variable $_POST remains empty. 如果我发出POST请求,其中未在请求标头中设置content-type,则变量$ _POST仍为空。

Question: How can I force PHP to fill $_POST? 问题:如何强制PHP填充$ _POST?

I encountered the problem making an Javascript AJAX request using XDomainRequest where you can not define any headers. 我遇到了使用XDomainRequest发出Javascript AJAX请求的问题,您无法定义任何标头。 Just to make it easier for you to understand the problem you can simulate the same effect without Javascript in PHP this way: 只是为了让您更容易理解这个问题,您可以通过这种方式在PHP中使用Javascript来模拟相同的效果:

$data = 'test=1';

$fp = fsockopen('www.yourpage.org', 80, $errno, $errstr, 5);
fputs($fp, "POST /test_out.php HTTP/1.1\r\n");
fputs($fp, "Host: www.yourpage.org\r\n");
//fputs($fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($fp, "Content-length: ". strlen($data) ."\r\n");
fputs($fp, "Connection: close\r\n\r\n");
fputs($fp, $data);

while(!feof($fp)) { echo fgets($fp, 128); }
fclose($fp);

test_out.php would be test_out.php会的

var_dump($_POST);

Without the correct content-type the variables in $_POST magically disappear . 没有正确的内容类型,$ _POST中的变量会神奇地消失

This is more an educational question. 这更像是一个教育问题。 I am asking this because most people here can not imaging that the content-type has this effect. 我问这个是因为这里的大多数人无法想象内容类型有这种效果。 I was asked to 'come back with facts'. 我被要求'回来说实话'。 So here you go. 所以,你走了。

You can override/inject the necessary header using Apache mod_headers if you have to. 如果必须,可以使用Apache mod_headers覆盖/注入必要的头。 Or otherwise resort to manually reconstructing the $_POST array. 或者以其他方式手动重建$ _POST数组。 (See also userland multipart/form-data handler ) (另请参见userland multipart / form-data handler

If it's always urlencoded, simply read from php://input (Which contains the raw POST request body) and use parse_str : 如果它总是urlencoded,只需从php://input (包含原始POST请求体)中parse_str并使用parse_str

parse_str(file_get_contents("php://input"), $_POST);

That should recreate the POST array, pretty much like PHP would do. 这应该重新创建POST数组,就像PHP一样。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM