[PHP]使用file_get_content來進行post request

在 php 程式中, 使用 curl 來進行 web request 是常用的方式, 不過由於在 https://repl.it/ 這個服務中, php webserver 並未安裝 curl, 所以需要改用 file_get_content()這個函數來進行 web request, 然而若為一般的 get request, 直接將網址傳入即可, 但若需要進行 post request 要如何操作呢?

這時會用到一個 http context options:

https://www.php.net/manual/en/context.http.php

範例程式如下:

<?php

$postdata = http_build_query(
    array(
        'var1' => 'some content',
        'var2' => 'doh'
    )
);

$opts = array('http' =>
    array(
        'method'  => 'POST',
        'header'  => 'Content-Type: application/x-www-form-urlencoded',
        'content' => $postdata
    )
);

$context  = stream_context_create($opts);

$result = file_get_contents('http://example.com/submit.php', false, $context);

?>

也就是利用了 http context options 來組合出要傳遞的參數. 如此一來便能很快速地應用在僅有 file_get_contents() 環境而沒有 curl 的 php webserver 環境來進行 post request.

參考資料:

https://stackoverflow.com/questions/2445276/how-to-post-data-in-php-using-file-get-contents

https://www.php.net/manual/en/context.http.php

 

在nodejs中發起json post的字元長度問題

在 nodejs 專案中, 若是需要對外發起使用 application/json 的 http post , 若有中文字, 需要注意計算字串長度的問題. 一般發起的程式碼請參考:

http://tech.pro/tutorial/1091/posting-json-data-with-nodejs

不過該範例是使用英文字, 所以沒有問題, 若是要發起中文字的 json http post, 需要調整計算 Content-Length 的方式, 使用 new Buffer(str).length, 如下:

var obj_json = { name: "王大頭", age: 25 };
var json_string = JSON.stringify(obj_json);

var req = http.request({
        host: 'host.example.com',
        port: 80,
        path: '/upload',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': new Buffer(json_string).length
        }
    }, function(res) {
    res.setEncoding('utf-8');
    var responseString = '';
    res.on('data', function(data) {
        responseString += data;
    });
    res.on('end', function() {        
        console.log(responseString);
    });
});

req.on('error', function(e) {
  // http post error
});    

req.write(json_string);
req.end();

參考資料: http://cnodejs.org/topic/50616f5301d0b801482695cf

分類
好用軟體

Tamper Data-好用的Firefox Debug工具

在 Firefox 中, 之前已經介紹過許多好用的工具(對開發及除錯應用), 像是

Firebug – https://diary.tw/archives/245, https://diary.tw/archives/485

Web Developer – https://diary.tw/archives/227

LiveHTTPHeaders – https://diary.tw/archives/565

Fiddler – https://diary.tw/archives/287

User Agent Switcher – https://diary.tw/archives/926

這裡要介紹的是除了可以觀察每個 http 連線狀況外, 還能修改傳送資料的功能, 這個 AddOn 稱之為 Tamper Data, 光看字面上就很清楚是一個改資料的 AddOn, 但是是在執行網頁訪問的狀況下可以用插入式的方式操作, 這對於在沒有開發工具下, 要快速地進行傳送資料的調整(header, postdata), 如此一來, 可以容易地進行除錯及測試驗證.

先安裝 tamper data 這個 Firefox 的 AddOn – https://addons.mozilla.org/en-us/firefox/addon/tamper-data/

接下來可以在 Tools (工具) 選單下出來一個 Tamper Data 選項, 點選出來後, 就會出現 Tamper Data 視窗, 接下來, 就可以正常訪問一般的網站, 例如 yahoo, 會看到畫面上有一堆 request 及 response time 的 list, 如下:

這樣對於訪問 yahoo 的結果可以一目暸然, 對任一筆資料按下右鍵, 選 [Graph All] 會出現一個有時間序的清單並圖象化, 如下: