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

Run Settings
LanguagePHP
Language Version
Run Command
<?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); }
<?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; }
Editor Settings
Theme
Key bindings
Full width
Lines