当前位置导航:炫浪网>>网络学院>>网页制作>>PHP教程

用PHP的Socket实现HTTP请求

最近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)."\r\n";}function sendRequest($sMethod = 'GET', $sPostData = ''){$sRequest = $sMethod." ".$this->sUri." HTTP/1.1\r\n";$sRequest .= $this->sRequestHeader;if ($sMethod == 'POST'){$sRequest .= "Content-Type: application/x-www-form-urlencoded\r\n";$sRequest .= "Content-Length: ".strlen($sPostData)."\r\n";$sRequest .= "\r\n";$sRequest .= $sPostData."\r\n";}$sRequest .= "\r\n";$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 = '/\r\n\r\n/';$arMatchResponsePart = preg_split($sPatternSeperate, $this->sResponse, 2);return $arMatchResponsePart[1];}function getResponseHead(){$sPatternSeperate = '/\r\n\r\n/';$arMatchResponsePart = preg_split($sPatternSeperate, $this->sResponse, 2);return $arMatchResponsePart[0];}}?>

相关内容
赞助商链接