search
尋找貓咪~QQ 地點 桃園市桃園區 Taoyuan , Taoyuan

PHP 如何透過 fsockopen 發送 HTTP Request (HTTP Client實作) - Soul & Shell Blog

在 PHP 中如果要實作 HTTP Client 來發送 Request,比較簡單的方式就是透過 cURL Library 來實現,但有時候 PHP 並沒有安裝 cURL,這時候就比較麻煩了。由於 HTTP 1.1 通訊時採用標準的 TCP/IP Socket 來連線,平常我們在進行低階的測試也可以用使用 telnet 指令來跟 HTTP Server 進行溝通,所以當沒有 cURL Library 可以使用時,我們也可以透過 PHP fsockopen 來實作 HTTP Client,以下就是透過 PHP fsockopen 發送 HTTP POST 的範例程式,程式會透過 fsockopen 呼叫另一個 XML WebService 來取得指定時區的時間:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
 
// 設定連線 URL
$url = 'http://127.0.0.1:8080/GetTimeWebService.php';
preg_match('/^(.+:\/\/)([^:\/]+):?(\d*)(\/.+)/', $url, $matches);
$protocol = $matches[1];
$host = $matches[2];
$port = $matches[3];
$uri = $matches[4];
 
// 設定等等要傳送的 XML 資料
$xml  = 'xml version="1.0" encoding="utf8" ?>';
$xml .= '<timezone>Asia/Taipei</timezone>';
 
// 開啟一個 TCP/IP Socket
$fp = fsockopen($host, $port, $errno, $errstr, 5);
if ($fp) {
    // 設定 header 與 body
    $httpHeadStr  = "POST {$url} HTTP/1.1\r\n";
    $httpHeadStr .= "Content-type: application/xml\r\n";
    $httpHeadStr .= "Host: {$host}:{$port}\r\n";
    $httpHeadStr .= "Content-Length: ".strlen($xml)."\r\n";
    $httpHeadStr .= "Connection: close\r\n";
    $httpHeadStr .= "\r\n";
    $httpBody = $xml."\r\n";
 
    // 呼叫 WebService
    fputs($fp, $httpHeadStr.$httpBody);
    $response = '';
    while (!feof($fp)) {
        $response .= fgets($fp, 2048);
    }
    fclose($fp);
 
    // 顯示回傳資料
    echo $response;
} else {
    die('Error:'.$errno.$errstr);
}

執行結果如下:

1
2
3
4
5
6
7
8
9
HTTP/1.1 200 OK
Date: Mon, 09 Jul 2012 08:56:02 GMT
Server: Apache/2.2.15 (CentOS)
X-Powered-By: PHP/5.3.3
Content-Length: 93
Connection: close
Content-Type: application/xml
 

GetTimeWebService.php 取得時區時間的 WebService 內容如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 
// 取得 HTTP Body 中的資料
$xml = file_get_contents('php://input');
 
// 使用正規表達式處理 XML (這是懶惰的寫法,不建議這樣做)
if (preg_match('/(.+)/', $xml, $matches)>0){
    // 設定時區
    $timezone = $matches[1];
    date_default_timezone_set($timezone);
 
    // 設定 header 與顯示時間
    header('Content-Type: application/xml');
    $xml  = 'xml version="1.0" encoding="utf8" ?>';
    $xml .= '<time timezone="'.$timezone.'">'.date('Y-m-d H:i:s').'</time>';
    echo $xml;
}

參考資料

平價童鞋首選



熱門推薦

本文由 toright 提供 原文連結

寵物協尋 相信 終究能找到回家的路
寫了7763篇文章,獲得2次喜歡
留言回覆
回覆
精彩推薦