美文网首页
PHP获取POST表单数据

PHP获取POST表单数据

作者: ieasy_tm | 来源:发表于2017-09-19 11:40 被阅读0次

php获取post表单数据,这是再正常不过的场景了,这里有几点需要注意,网上也都有提到。别人总结的毕竟不是自己的,为了体会这些注意点,我自己在本地搭建一个web application, 然后去验证。注意点是:

$_POST
file_get_contents("php://input")
$GLOBALS['HTTP_RAW_POST_DATA']

这三者到底有什么却别?上前端代码:

<form name="form1" id="form1" method="post" action="index.php" enctype="application/x-www-form-urlencoded">
        <fieldset class="form">
                <p>
                    <label class="loginlabel" for="user_name">
                        Username:</label>
                    <input class="logininput ui-keyboard-input ui-widget-content ui-corner-all" name="user_name"
                        id="user_name" type="text" value="" />
                </p>
                <p>
                    <label class="loginlabel" for="user_password">
                        Password:</label>
                    <span>
                        <input class="logininput"   name="user_password" id="user_password" type="password" /><img
                            id="passwd" class="tooltip" alt="Click to open the virtual keyboard" title="Click to open the virtual keyboard"
                            src="keyboard.png" /></span>
                </p>
            </fieldset>

上php代码:

<?php
var_dump($_POST);
var_dump(file_get_contents("php://input"));
var_dump($GLOBALS["HTTP_RAW_POST_DATA"]);

这三种获取POST表单数据的方式跟前端提交表单的enctype(entity-body coding type)有关系,浏览器会在request的Content-type字段给出post表单数据的编码方式。常见的编码方式:

1. URLencoded: application/x-www-form-urlencoded
2. Multipart: multipart/form-data
3. JSON: application/json
4. XML: text/xml
5. 纯文本: text/plain

在Web开发中,前三种格式非常常见。HTML中<form>支持urlencoded,multipart,plain text, 通过enctype属性来进行设置。AJAX中默认的则是JSON编码格式。我配置了下php.ini中的 always_populate_raw_post_data = On。测试结果如下:

content_type = application/x-www-form-urlencoded => $_POST 和 file_get_contents("php://input")都可以获取表单数据,至于$GLOBALS['HTTP_RAW_POST_DATA']能不能就得看php.ini的配置了。

content_type = multipart/form-data =>  file_get_contents("php://input") 和 $GLOBALS['HTTP_RAW_POST_DATA']都获取不到数据,但$_POST可以,这点结论与网上其他文章不一样

content_type = text/plain => $_POST获取不到数据,file_get_contents("php://input")和$GLOBALS['HTTP_RAW_POST_DATA']可以获取到

content_type = application/json => $_POST 和 file_get_contents("php://input")都可以获取表单数据, $GLOBALS['HTTP_RAW_POST_DATA']不行

这里简单记录下POST表单数据的读取问题,网上针对这个问题的文章很多,这里只是简单备忘和验证。
end~

相关文章

网友评论

      本文标题:PHP获取POST表单数据

      本文链接:https://www.haomeiwen.com/subject/ypfisxtx.html