最近HTTP遠端存取的程式寫得多了,主要接觸的是.NET類別庫裡的WebHttpRequest類別和Microsoft.XMLHTTP這個通用的對象,有了這些方便的類,我們可以透過C#,ASP,Javascript來模擬Web客戶端存取其他的Web頁面。但今天想用PHP實現類似的功能,卻一時找不到方向了,於是只能自己「豐衣足食」了。
目前,PHP裡面還沒有類似於HttpRequest的類,不過在官方在線文檔中找到了這麼一個HttpRequest Class的頁面,不過也只是提及了此功能目前可能只有在CVS版本中存在,無奈...
要實現HTTP存取無非就是用Socket傳送一個請求,然後讀取回傳訊息。於是我就用Socket寫了一個HttpRequest的類,當然也可以用fsockopen()這個函數來實現,不過兩個的區別不是很大,具體程式碼在附件裡,自己看咯。
<?php/*** Network: HTTP request object* Author: Li HouYu (Karajan Lee), Shanghai, China.*/class HttpRequest{var $sHostAdd;var $sUri;var $iPort;var $sRequestHeader;var $sResponse ;function HttpRequest($sUrl){$sPatternUrlPart = '/http://([az-.0-9]+)(:(d+)){0,1}(.*)/i' ;$arMatchUrlPart = array();preg_match($sPatternUrlPart, $sUrl, $arMatchUrlPart);$this->sHostAdd = gethostbyname($arMatchUrlPart[1]);if (empty($arMatchUrlPart[4]); >sUri = '/';}else{$this->sUri = $arMatchUrlPart[4];}if (empty($arMatchUrlPart[3])){$this->iPort = 80;}else{$this-> iPort = $arMatchUrlPart[3];}$this->addRequestHeader('Host: '.$arMatchUrlPart[1]);$this->addRequestHeader('Connection: Close');}function addRequestHeader($sHeader){$this ->sRequestHeader .= trim($sHeader)."rn";}function sendRequest($sMethod = 'GET', $sPostData = ''){$sRequest = $sMethod." ".$this->sUri ." HTTP/1.1rn";$sRequest .= $this->sRequestHeader;if ($sMethod == 'POST'){$sRequest .= "Content-Type: application/x-www-form-urlencoded rn";$sRequest .= "Content-Length: ".strlen($sPostData)."rn";$sRequest .= "rn";$sRequest .= $sPostData." rn";}$sRequest .= "rn";$sockHttp = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);if (!$sockHttp){die('socket_create() failed!');}$resSockHttpp = socket_connect($sockHttp, $this->sHostAdd, $this->iPort);if (!$resSockHttp){die('socket_connect() failed!');}socket_write($sockHttp, $sRequest, strlen($sRequest ));$this->sResponse = '';while ($sRead = socket_read($sockHttp, 4096)){$this->sResponse .= $sRead;}socket_close($sockHttp);}function getReponse(. $this->sResponse;}function getResponseBody(){$sPatternSeperate = '/rnrn/';$arMatchResponsePart = preg_split($sPatternSeperate, $this->sResponse, 2); ];}function getResponseHead(){$sPatternSeperate = '/rnrn/';$arMatchResponsePart = preg_split($sPatternSeperate, $this->sResponse, 2);return $arMatchResponse}Part[0]; ?>