浏览 4882 次
锁定老帖子 主题:用PHP的Socket实现HTTP请求
精华帖 (0) :: 良好帖 (0) :: 新手帖 (0) :: 隐藏帖 (0)
|
|
---|---|
作者 | 正文 |
发表时间:2008-01-24
目前,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]; } } ?> 声明:ITeye文章版权属于作者,受法律保护。没有作者书面许可不得转载。
推荐链接
|
|
返回顶楼 | |
发表时间:2008-03-27
有snoopy
http://sourceforge.net/projects/snoopy/ |
|
返回顶楼 | |