file_get_contents('php://input') 和POST的區別


之前記得寫過這2者的區別,今天看群里有個朋友也提出了怪異的問題,說是“file_get_contents('php://input')獲取不到curl post請求的數據的問題”?
其實這並不是所謂的"怪異",理解2者的區別其實就明白原因啦,好,直接舉個例子吧,2個文件:
1:發送數據的文件,如下:

復制代碼
<?php
$ch = curl_init();
$data = ['username' => '周伯通', 'password' => '123456','sign'=>'asdfg123456'];
$url = 'http://xxx.com/fpost.php';//fpost.php是接受數據的文件,代碼在下面
$ch = curl_init(); //初始化curl
curl_setopt($ch, CURLOPT_URL, $url);//設置鏈接
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);//設置是否返回信息
curl_setopt($ch, CURLOPT_POST, 1);//設置為POST方式
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);//POST數據
curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)");
$response = curl_exec($ch);//接收返回信息
if(curl_errno($ch)){//出錯則顯示錯誤信息
    print curl_error($ch);
}
curl_close($ch); //關閉curl鏈接
echo $response;//顯示返回信息
復制代碼

2:接受數據的文件,如下:

<?php
$res = file_get_contents('php://input');
var_dump('file_get_contents 數據是:'.$res);
echo'<br> post 數據是:';
var_dump($_POST);

運行后我們會發現:file_get_contents('php://input')不能接收curl post過來的數組。

解釋:
如果POST的原始數據是一維數組或&拼接的標准格式的鍵值對字符串,那么可以用$_POST來獲取。
如果要通過file_get_contents獲取,這種情況下可以發送json字符串,用json_encode轉一下,或者使用http_build_query:比如上面修改如下:

curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));//POST數據

結果:

string(97) "file_get_contents 數據是:username=%E5%91%A8%E4%BC%AF%E9%80%9A&password=123456&sign=asdfg123456" 
post 數據是:array(3) { ["username"]=> string(9) "周伯通" ["password"]=> string(6) "123456" ["sign"]=> string(11) "asdfg123456" }

所以大家在使用中,注意下傳參的方式即可解決問題。無非就這2種比較常用的數據傳參方式啦。

原文:https://www.cnblogs.com/phpper/p/9574419.html


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM