note 70064 added to ref.sockets

From: Date: Mon, 02 Oct 2006 06:50:42 +0000
Subject: note 70064 added to ref.sockets
Groups: php.notes 
Request: Send a blank email to php-notes+get-117927@lists.php.net to get a copy of this message
A simple HTTP request class using socket. <?php 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]; } } ?> ---- Server IP: 66.163.161.117 Probable Submitter: 211.161.245.175 ---- Manual Page -- http://www.php.net/manual/en/ref.sockets.php Edit -- https://master.php.net/note/edit/70064 Del: integrated -- https://master.php.net/note/delete/70064/integrated Del: useless -- https://master.php.net/note/delete/70064/useless Del: bad code -- https://master.php.net/note/delete/70064/bad+code Del: spam -- https://master.php.net/note/delete/70064/spam Del: non-english -- https://master.php.net/note/delete/70064/non-english Del: in docs -- https://master.php.net/note/delete/70064/in+docs Del: other reasons-- https://master.php.net/note/delete/70064 Reject -- https://master.php.net/note/reject/70064 Search -- https://master.php.net/manage/user-notes.php

« previous php.notes (#117927) next »