$_POST、$HTTP_RAW_POST_DATA、php://input

1. $_POST

Content-Type仅在取值为application/x-www-data-urlencoded和multipart/form-data两种情况下,PHP才会将http请求数据包中相应的数据填入全局变量$_POST,而如果客户端向服务器post的数据是xml等格式时,$_POST是接收不了的

2. php://input

通常情况下,http_build_query($_POST) =  file_get_contents("php://input");

当enctype="multipart/form-data" 的时候 php://input 是无效的。

3. $HTTP_RAW_POST_DATA

$HTTP_RAW_POST_DATA已在php5.6版本中废弃,官方建议使用php://input替代

4. HTTP POST请求数据传输方式

(1)application/x-www-form-urlencoded

原生 form 表单默认方式:application/x-www-form-urlencoded 方式提交数据

Content-Type:application/x-www-form-urlencoded

name=Donald+Duck&city=%E6%9D%AD%E5%B7%9E 

前端

<!DOCTYPE html>
<html>
<head>
    <script src="http://www.htmleaf.com/js/jquery/1.11.1/jquery.min.js">
    </script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $.ajax({
                    type: 'POST',
                    url: 'http://wx.com/index.php/index/test/index',
                    data: {
                                name:"Donald Duck",
                                city:"杭州"
                    },
                    dataType: 'json',
                    //默认:
                    // contentType: 'application/x-www-form-urlencoded',
                    success:function(data){
                        alert(data.name);
                    },
                    error:function(e){
                        alert("错误!!");
                    }
                });
            });
        });
    </script>
</head>
<body>

<button>向页面发送 HTTP POST 请求,并获得返回的结果</button>

</body>
</html>

后端

    public function index()
    {
        header('content-type:application:json;charset=utf8');
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:POST');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
        $ret = request()->param();
//        $ret = file_get_contents("php://input");
        echo json_encode($ret);

    }

php://input    返回字符串 name=Donald+Duck&city=%E6%9D%AD%E5%B7%9E

request()->param() 返回数组 array(2) { ["name"]=> string(11) "Donald Duck" ["city"]=> string(6) "杭州" }

(2)multipart/form-data

表单上传文件时, form 的 enctyped 必须设置为当前这个值。

Content-Type:multipart/form-data; boundary=----WebKitFormBoundarysngHPnlMJCdmGAOt

------WebKitFormBoundarysngHPnlMJCdmGAOt

Content-Disposition: form-data; name="file"; filename="2000776.jpg"

Content-Type: image/jpeg

------WebKitFormBoundarysngHPnlMJCdmGAOt--

前端

<!DOCTYPE html>
<html>
<head>
    <script src="http://www.htmleaf.com/js/jquery/1.11.1/jquery.min.js">
    </script>
    <script>
        function sendToUser(){ //在这里进行ajax 文件上传 用户的信息
            var type = "file";
            var formData = new FormData();//这里需要实例化一个FormData来进行文件上传
            formData.append(type,$("#fileName1")[0].files[0]);
            $.ajax({
                type : "post",
                url : "http://wx.com/index.php/index/test/index",
                data : formData,
                processData : false,
                contentType : false,
                success : function(data){
                    alert(data);
                }
            });
        }
    </script>
</head>
<body>
<input type="file" name="fileName1" id="fileName1"/>
<input type="button" onclick="sendToUser()" id="sendToUser" value="提交" />
</body>
</html>

后端

public function index()
    {
        header('content-type:application:json;charset=utf8');
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:POST');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');

        $file = request()->file('file');
        // 移动到框架应用根目录/uploads/ 目录下
        $info = $file->move( '../uploads');
        if($info){
            // 成功上传后 获取上传信息
            return json($info->getFilename());
        }else{
            // 上传失败获取错误信息
            return json($file->getError());
        }

    }
request()->file('file') 文件信息
php://input 没数据

(3)application /json

序列化后的 JSON 字符串格式,JSON 格式支持比键值对复杂得多的结构化数据,方便提交复杂的数据,特别适合 RESTful 的接口。

Content-Type:application/json

 

{name: "Donald Duck", city: "杭州"}

前端

<!DOCTYPE html>
<html>
<head>
    <script src="http://www.htmleaf.com/js/jquery/1.11.1/jquery.min.js">
    </script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $.ajax({
                    type: 'POST',
                    url: 'http://wx.com/index.php/index/test/index',
                    data: '{"name":"Donald Duck","city":"杭州"}',
                    dataType: 'json',
                    contentType: 'application/json',
                    success:function(data){
                        alert(data);
                    },
                    error:function(e){
                        alert("错误!!");
                    }
                });
            });
        });
    </script>
</head>
<body>
<button>向页面发送 HTTP POST 请求,并获得返回的结果</button>
</body>
</html>

后端

public function index()
    {
        header('content-type:application:json;charset=utf8');
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:POST');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');
        $ret = file_get_contents("php://input");
        var_dump(json_decode($ret,true));

    }

request()->param() 返回数组 array(2) { ["name"]=> string(11) "Donald Duck" ["city"]=> string(6) "杭州" }

php://input    返回字符串 string(38) "{"name":"Donald Duck","city":"杭州"}"  可json_decode 成对象

(4)text/xml

XML-RPC(XML Remote Procedure Call)XML-RPC消息就是一个请求体为xml的http-post请求

Content-Type:text/xml

<user><username>测试</username></user>

前端

<!DOCTYPE html>
<html>
<head>
    <script src="http://www.htmleaf.com/js/jquery/1.11.1/jquery.min.js">
    </script>
    <script>
        $(document).ready(function(){
            $("button").click(function(){
                $.ajax({
                    type: 'POST',
                    url: 'http://wx.com/index.php/index/test/index',
                    data: "<user><username>测试</username></user>",
                    dataType: 'json',
                    contentType: 'text/xml',
                    success:function(data){
                        alert(data.username);
                    },
                    error:function(e){
                        alert("错误!!");
                    }
                });
            });
        });
    </script>
</head>
<body>
<button>向页面发送 HTTP POST 请求,并获得返回的结果</button>
</body>
</html>

后端

    public function index()
    {
        header('content-type:application:json;charset=utf8');
        header('Access-Control-Allow-Origin:*');
        header('Access-Control-Allow-Methods:POST');
        header('Access-Control-Allow-Headers:x-requested-with,content-type');

//        $ret = request()->param();
        $ret = file_get_contents("php://input");
        $res = simplexml_load_string($ret);
        return json($res);

    }

request()->param() 无数据

php://input    返回字符串 string(40) "<user><username>测试</username></user>" 用simplexml_load_string()获取对象

注意: 

  • content-type 为 "application/json" 的数据 PHP 是不能直接识别的,ThinkPHP5 无法接收 客户端 Post 传递的 Json 参数

  • 可以通过 file_get_contents('php://input') 直接获取到传入的 Json 参数

`file_get_contents('php://input')` 是 PHP 中一个常用的函数,用于读取原始的 HTTP 请求体数据。这个函数在处理 POST 请求时特别有用,尤其是当请求的数据不是表单编码(如 `application/x-www-form-urlencoded` 或 `multipart/form-data`)时,比如 JSON 或 XML 数据。 ### 使用场景 1. **处理 JSON 数据**:当客户端发送 JSON 格式的数据时,可以通过 `file_get_contents('php://input')` 获取原始的 JSON 字符串,然后使用 `json_decode` 将其转换为 PHP 对象或数组。 2. **处理 XML 数据**:类似地,当客户端发送 XML 格式的数据时,可以通过这个函数获取原始的 XML 字符串,然后使用 `simplexml_load_string` 或其他 XML 解析库进行解析。 3. **处理二进制数据**:当需要处理上传的二进制数据(如文件上传)时,也可以使用这个函数获取原始的二进制数据。 ### 示例代码 ```php <?php // 获取原始的 HTTP 请求体数据 $rawData = file_get_contents('php://input'); // 假设客户端发送的是 JSON 数据 $data = json_decode($rawData, true); if ($data === null) { // 处理 JSON 解码错误 http_response_code(400); echo json_encode(['error' => 'Invalid JSON']); exit; } // 处理数据 echo json_encode(['status' => 'success', 'data' => $data]); ?> ``` ### 优点 - **灵活性**:可以处理各种格式的数据,而不仅仅是表单数据。 - **性能**:直接读取原始数据,避免了 PHP 自动解析表单数据的开销。 ### 注意事项 - **数据长度**:对于非常大的请求体,读取数据可能会消耗大量内存,需要注意数据长度。 - **安全性**:确保对读取到的数据进行适当的验证和消毒,以防止安全漏洞。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值