本文學習目的:
為什么和第三方平臺對接接口的時候,在接收http請求數(shù)據(jù)包時,一般都是用file_get_contents("php://input"),而不是用$_POST呢?
file_get_contents:將整個文件讀入一個字符串
在用php寫接口的時候,通常會將請求的數(shù)據(jù)通過json的形式發(fā)送到指定的請求地址處,此時的file_get_contents(‘php://input')主要是用來獲取請求的原始數(shù)據(jù)。和 $HTTP_RAW_POST_DATA 比起來,php://input給內(nèi)存帶來的壓力較小,并且不需要任何特殊的 php.ini 設置。
注意兩點:
數(shù)據(jù)的提交方式應為POSTphp://input 不能用于接收enctype="multipart/form-data"表單提交的數(shù)據(jù)
1、舉一個簡單示例:
提交表單
form action="" method="POST">
姓名: input type="text" name="name" value="tom" />br />
年齡:input type="text" name="age" value="22" />br />
input type="submit" value="Submit" />
/form>
后端控制器通過file_get_contents(‘php://input'),獲取請求原始數(shù)據(jù)流
?php
$content = file_get_contents('php://input', 'r');
echo $content;
//輸出name=tomage=22
?>
2、在項目應用中,如攝像頭拍照,上傳保存,就可以用到php://input。客戶端拍照后,把圖片流傳送到服務端,服務端使用file_get_getcontents(‘php://input')就能獲取到圖片流。
$_POST
$_POST只能接收Content-Type: application/x-www-form-urlencoded提交的數(shù)據(jù),php會將http請求body相應數(shù)據(jù)填入到數(shù)組_POST中,_POST數(shù)組中的數(shù)據(jù)是進行urldecode()解析的結(jié)果。除了該Content-Type,還有 multipart/form-data類型的表單數(shù)據(jù)也可以用$_POST接收。
四種常見的提交數(shù)據(jù)方式,分別如下:
定義和用法
enctype 屬性規(guī)定在發(fā)送到服務器之前應該如何對表單數(shù)據(jù)進行編碼。默認地,表單數(shù)據(jù)會編碼為 "application/x-www-form-urlencoded"。就是說,在發(fā)送到服務器之前,所有字符都會進行編碼(空格轉(zhuǎn)換為 "+" 加號,特殊符號轉(zhuǎn)換為 ASCII HEX 值)。
enctype屬性值
Content-Type值 |
描述 |
application/x-www-form-urlencoded |
在發(fā)送前編碼所有字符(默認) |
multipart/form-data |
不對字符編碼。
在使用包含文件上傳控件的表單時,必須使用該值。
|
text/plain |
空格轉(zhuǎn)換為 "+" 加號,但不對特殊字符編碼。 |
text/xml
|
一種使用 HTTP 作為傳輸協(xié)議,XML 作為編碼方式的遠程調(diào)用規(guī)范。 |
總結(jié):
1、Coentent-Type僅在取值為application/x-www-data-urlencoded和multipart/form- data兩種情況下,PHP才會將http請求數(shù)據(jù)包中相應的數(shù)據(jù)填入全局變量$_POST中。
2、PHP不能識別的Content-Type類型的時候,會將http請求包中相應的數(shù)據(jù)填入變量$HTTP_RAW_POST_DATA中。
3、只有Coentent-Type為multipart/form-data的時候,PHP才不會將http請求數(shù)據(jù)包中的相應數(shù)據(jù)填入php: //input,否則其它情況都會。填入的長度,由Coentent-Length指定。
4、只有Content-Type為application/x-www-data-urlencoded時,php://input數(shù)據(jù)才跟$_POST數(shù)據(jù)相一致。
5、如果不能獲取的時候,比如Coentent-Type為text/xml、application/json、soap,請使用 file_get_contents('php://input');
到此這篇關于php使用file_get_contents(‘php://input‘)和$_POST的區(qū)別實例對比的文章就介紹到這了,更多相關php使用file_get_contents和$_POST內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
您可能感興趣的文章:- 解決PHP curl或file_get_contents下載圖片損壞或無法打開的問題
- php中file_get_contents()函數(shù)用法實例
- PHP使用file_get_contents發(fā)送http請求功能簡單示例
- PHP使用fopen與file_get_contents讀取文件實例分享
- PHP中file_get_contents函數(shù)抓取https地址出錯的解決方法(兩種方法)