WEB언어/PHP
[펌] PHP - tcp소켓 통신을 이용한 HTTP Request
saltdoll
2008. 11. 4. 10:29
반응형
File name : httpRequest.php
method =strtoupper($method);
$this->host =$host;
$this->port =$port;
$this->path =$path;
$this->errno =$errno;
$this->errstr =$errstr;
$this->timeout =$timeout;
$this->query = $query;
}
function openSocket() {
$this->fp = fsockopen($this->host,$this->port,$this->errno,$this->errstr,$this->timeout);
}
function closeSocket() {
fclose($this->fp);
}
// put header to connected socket
function putHeader() {
// if request method is GET, query attached the end of URL
$getQuery = $this->method == strtoupper("GET") ? "?".$this->query : "";
fputs($this->fp, $this->method." ".$this->path.$getQuery." / HTTP/1.1\r\n");
fputs($this->fp, "Host: ".$this->host."\r\n");
fputs($this->fp, "Content-type: application/x-www-form-urlencoded\r\n");
fputs($this->fp, "Content-length: ".strlen($this->query)."\r\n");
fputs($this->fp, "Connection: close\r\n\r\n");
}
//put query to connected socket (only POST)
function putQuery() {
fputs($this->fp, $this->query . "\r\n\r\n");
}
// Gets responsed value(by line) from connected socket
function getResponse() {
while(!feof($this->fp))
{
$result .= fgets($this->fp, 1024);
}
$this->result = $result;
}
// partitioning Header,Body
function getResult() {
$tmp = explode("\r\n\r\n",$this->result); // Split a string by (CRLF *2)
$this->resultHeader = $tmp[0];
$this->resultBody = $tmp[1];
}
function sendRequest() {
$this->openSocket();
$this->putHeader();
if($this->method == strtoupper("POST")) $this->putQuery();
$this->getResponse();
$this->getResult();
$this->closeSocket();
}
}
?>
File name : shootRequest.php
sendRequest();
if($argv[2] == strtolower("h")) $result = $request->resultHeader; // print responsed header
elseif($argv[2] == strtolower("b")) $result = $request->resultBody; // print responsed body
else $result = $request->result; // print responsed all
print($result);
?>
위의 코드는 naver 검색페이지에서 특정 문장을 검색하는 코드입니다.
네이버 검색페이지는 외부에서 POST 지원을 않하는것 같습니다..
GET 으로 request를 날려 보겠습니다.
D:\Project\localhost >php shootRequest.php g h
파일명뒤의 g, h 옵션은~
g: GET 으로 쏘겠다는 것 입니다. (p 로 하시면 POST로 쏩니다.)
h: request에 대한 response 를 header 만 보겠다는 것 입니다.
(b 는 body, 아무것도 안넣으면 heaer + body)
대충 넣은 옵션 처리입니다. 코드 훓어 보면 아실겁니다.
물론 웹에서도 가능합니다. shootRequest.php 의 $method 를 "GET" 으로 고정시키고
웹에서 shootRequest.php 를 실행시키면 위의 코드가 어떤것인지 한눈에 알 수 있습니다.
반응형