class http {
private $host;
private $port = 80;
private $path;
private $timeout;
private $method;
private $data;
private $length;
private $fp;
public function __construct($url = '', $method = 'GET', $data = '', $timeout = 60) {
if ($url != '') {
$this->setUrl($url);
}
$this->setMethod($method);
$this->setData($data);
$this->setTimeout($timeout);
}
public function setUrl($url) {
$parseArr = parse_url($url);
if (isset($parseArr['host'])) {
$this->host = $parseArr['host'];
}
if (isset($parseArr['port'])) {
$this->port = $parseArr['port'];
}
if (isset($parseArr['path'])) {
$this->path = $parseArr['path'];
} else {
$this->path = "/";
}
if (isset($parseArr['query'])) {
$this->path .= $parseArr['query'];
}
}
public function setTimeout($timeout) {
$this->timeout = $timeout;
}
public function setMethod($method) {
$this->method = strtoupper($method);
}
public function setData($data) {
$this->data = $data;
$this->length = strlen($this->data);
}
public function execute() {
$this->fp = fsockopen($this->host, $this->port, $errno, $errstr, $this->timeout);
if (!$this->fp) {
throw new Exception("{$errstr} : {$errno}");
}
stream_set_blocking($this->fp, 0);
stream_set_timeout($this->fp, $this->timeout);
if (strcmp($this->method, 'GET') === 0) {
$this->get();
} else {
$this->post();
}
while (!feof($this->fp)) {
if (($header = fgets($this->fp)) && ($header == "\r\n" || $header == "\n")) {
break;
}
}
$body = '';
while (!feof($this->fp)) {
$body .= fgets($this->fp, 4096);
}
fclose($this->fp);
return $body;
}
public function get() {
fwrite($this->fp, "{$this->method} {$this->path} HTTP/1.1\r\n");
fwrite($this->fp, "Accept: */*\r\n");
fwrite($this->fp, "Host: {$this->host}\r\n");
fwrite($this->fp, "Connection: Close\r\n\r\n");
}
public function post() {
fwrite($this->fp, "{$this->method} {$this->path} HTTP/1.1\r\n");
fwrite($this->fp, "Accept: */*\r\n");
fwrite($this->fp, "Content-Type: application/x-www-form-urlencoded\r\n");
fwrite($this->fp, "Host: {$this->host}\r\n");
fwrite($this->fp, "Content-Length: {$this->length}\r\n");
fwrite($this->fp, "Connection: Close\r\n");
fwrite($this->fp, "Cache-Control: no-cache\r\n\r\n");
fwrite($this->fp, $this->data);
}
}
?>