php虚拟类,PHP http请求模拟类

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);

}

}

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值