sokite

时间:2022-05-11 12:07:44

<?php

interface Proto {

//连接
function conn($url);
//发送get请求
function get();
//发送post请求
function post();
//关闭连接
function close($f);

}

class Http implements Proto {

const CRLF = "\r\n";

protected $errno = -1;
protected $errstr = '';
protected $response = '';
protected $timeout = 3;

protected $url = null;
protected $version = 'HTTP/1.1';
protected $fh = null;

protected $line = array();
protected $header = array();
protected $body = array();

public function __construct($url){
$this->conn($url);
$this->setHeader('Host:'.$this->url['host']);
}

//写请求行
public function setLine($method){
$this->line[0] = $method . ' ' . $this->url['path'].'?'.$this->url['query'] . ' '. $this->version;
}

//写头信息
protected function setHeader($headerline){
$this->header[] = $headerline;
}
//写主体信息
protected function setBody($body){
$this->body[] =http_build_query($body);
}
//连接
public function conn($url){
$this->url = parse_url($url);
//判断多口
if(!isset($this->url['port'])){
$this->url['port'] = 80;
}
//fsockopen — 打开一个网络连接或者一个Unix套接字连接
$this->fh = fsockopen($this->url['host'],$this->url['port'],$this->errno,$this->errstr,$this->timeout);
}

//发送get请求
public function get(){
$this->setLine('GET');
$this->request();
return $this->response;
}
//发送post请求
public function post($body=array()){
$this->setLine('POST');
$this->setBody($body);

$this->setHeader('Content-Type: application/x-www-form-urlencoded'.self::CRLF.'Content-Length:'.strlen($this->body[0]));
$this->request();
return $this->response;
}
//真正请求
public function request(){
//请求行,头信息,实体信息,放在同一个数组,便于拼接
$req = array_merge($this->line,$this->header,array(''), $this->body ,array(''));
$req = implode(self::CRLF, $req );
// print_r($this);
// print_r($req);
// die;

fwrite($this->fh, $req);
while (!feof($this->fh)) {
$this->response .= fread($this->fh, 512) ;
}
$this->close($this->fh);

}
//关闭连接
public function close($f){
fclose($f);
}

}

/*
//循环灌水
set_time_limit(0);
for($i = 0; $i<10; $i++){
$str = str_shuffle('abcdefjghiqeuoiqutqkldfjmnzbcznasdjkhfaklwghtbfvh12354654879');
$data = array(
'dname' => substr($str, 0,5),
'xname' => substr($str, 6,9),
'intro' => substr($str, 10,16),
'cat_id' =>''
);
$url = 'http://127.0.0.1/shang/admin/boardAct.php';
$http = new Http($url);
echo $http->post($data);
}
*/

// $url = 'http://127.0.0.1/shang/a1.php';
// $http = new Http($url);
// echo $http->get();

$url = 'http://127.0.0.1/shang/a1.php?d=3&c=1';
$http = new Http($url);
echo $http->post(array(1=>1,2=>2));

相关文章