程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> 網頁編程 >> PHP編程 >> 關於PHP編程 >> 用PHP的Socket實現HTTP請求

用PHP的Socket實現HTTP請求

編輯:關於PHP編程

最近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://([a-z-.0-9]+)(:(d+)){0,1}(.*)/i;$arMatchUrlPart = array();preg_match($sPatternUrlPart, $sUrl, $arMatchUrlPart);$this->sHostAdd = gethostbyname($arMatchUrlPart[1]);if (empty($arMatchUrlPart[4])){$this->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)." ";}function sendRequest($sMethod = GET, $sPostData = ){$sRequest = $sMethod." ".$this->sUri." HTTP/1.1 ";$sRequest .= $this->sRequestHeader;if ($sMethod == POST){$sRequest .= "Content-Type: application/x-www-form-urlencoded ";$sRequest .= "Content-Length: ".strlen($sPostData)." ";$sRequest .= " ";$sRequest .= $sPostData." ";}$sRequest .= " ";$sockHttp = socket_create(AF_INET, SOCK_STREAM, SOL_TCP);if (!$sockHttp){die(socket_create() failed!);}$resSockHttp = 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 getResponse(){return $this->sResponse;}function getResponseBody(){$sPatternSeperate = / /;$arMatchResponsePart = preg_split($sPatternSeperate, $this->sResponse, 2);return $arMatchResponsePart[1];}function getResponseHead(){$sPatternSeperate = / /;$arMatchResponsePart = preg_split($sPatternSeperate, $this->sResponse, 2);return $arMatchResponsePart[0];}}?>

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved