fbpx

PHP 如何透過 fsockopen 發送 HTTP Request (HTTP Client實作)

在 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 來取得指定時區的時間:

<?php

// 設定連線 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);
}

執行結果如下:

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

<?xml version="1.0" encoding="utf8" ?><time timezone="Asia/Taipei">2012-07-09 16:56:02</time>

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

<?php

// 取得 HTTP Body 中的資料
$xml = file_get_contents('php://input');

// 使用正規表達式處理 XML (這是懶惰的寫法,不建議這樣做)
if (preg_match('/<timezone>(.+)<\/timezone>/', $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;
}

參考資料

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *

這個網站採用 Akismet 服務減少垃圾留言。進一步了解 Akismet 如何處理網站訪客的留言資料