Quick actions

cmd+k|ctrl+k

Navigation

Languages

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

Snippet info

Language

Php

Visibility

public

Author

mosi

Created

2018-12-07T13:25:36Z

Updated

2018-12-07T13:25:36Z

<?php
 
// 設定連線 URL
$url = './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);
}
INFO