新聞中心
這篇文章給大家分享的是有關php如何實現(xiàn)輸入輸出流的內(nèi)容。小編覺得挺實用的,因此分享給大家做個參考,一起跟隨小編過來看看吧。
為了更好理解http協(xié)議,看了一下nodejs的http的模塊!感覺收獲還是挺多的。比如我用http的request發(fā)一個請求:
var options = { host: 'localhost', port: 80, path: '/backbone/data.php', method: 'POST' }; var req = http.request(options, function(res) { console.log('STATUS: ' + res.statusCode); console.log('HEADERS: ' + JSON.stringify(res.headers)); res.setEncoding('utf8'); res.on('data', function (chunk) { console.log('BODY: ' + chunk); }); }); // write data to request body req.end('name=liuzhang&age=28');
上述代碼的意思是發(fā)送數(shù)據(jù)'name=liuzhang&age=28',回調(diào)是響應的對象,把服務器響應的數(shù)據(jù)打印出來!
data.php 代碼是
print_r($_POST);
打印傳過來的數(shù)據(jù)!
在命令行運行的結(jié)果是
可以看到Array是空,就是$_POST 沒有數(shù)據(jù),一開始我以為是數(shù)據(jù)沒有傳過來!但是我把后端data.php 改成
echo file_get_contents("php://input");
接收到了傳過來的數(shù)據(jù)!
php://input 是個可以訪問請求的原始數(shù)據(jù)的只讀流。 POST 請求的情況下,好使用 php://input 來代替 $HTTP_RAW_POST_DATA,因為它不依賴于特定的 php.ini 指令。 而且,這樣的情況下 $HTTP_RAW_POST_DATA 默認沒有填充, 比激活 always_populate_raw_post_data 潛在需要更少的內(nèi)存。 enctype="multipart/form-data" 的時候 php://input 是無效的。
$_POST僅當數(shù)據(jù)按 application/x-www-form-urlencoded 類型提交時才能得到,form的enctype屬性為編碼方式,常用有兩種:application/x-www-form-urlencoded和multipart/form-data,默認為application/x-www-form-urlencoded。 當action為get時候,瀏覽器用x-www-form-urlencoded的編碼方式把form數(shù)據(jù)轉(zhuǎn)換成一個字串(name1=value1&name2=value2...),然后把這個字串a(chǎn)ppend到url后面,用?分割,加載這個新的url。 當action為post時候,瀏覽器把form數(shù)據(jù)封裝到http body中,然后發(fā)送到server。
當我們把發(fā)送options改成
var options = { host: 'localhost', port: 80, path: '/backbone/data.php', method: 'POST', headers : {'Content-Type': 'application/x-www-form-urlencoded'} };
加上一個headers content-type 就可以用$_POST 接收到數(shù)據(jù)! 如果不是這種的form類型,你就可以用原始的輸入接收數(shù)據(jù)!
感謝各位的閱讀!關于“php如何實現(xiàn)輸入輸出流”這篇文章就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,讓大家可以學到更多知識,如果覺得文章不錯,可以把它分享出去讓更多的人看到吧!
標題名稱:php如何實現(xiàn)輸入輸出流-創(chuàng)新互聯(lián)
文章起源:http://fisionsoft.com.cn/article/dcooes.html