class Http {
public $lineAndHeader;
public $path;
public $method;
public $port = 80;
public $version = 'HTTP/1.1';
public function __construct($url)
{
$this->path=parse_url($url);
$this->setLine();
}
//设置请求行
public function setLine()
{
if(!isset($this->path['query'])){
$this->path['query'] = null;
}
return array($this->method.' '.$this->path['path'].'?'.$this->path['query'].' '.$this->version);
}
//设置头信息
public function setHeader($header = array())
{
if(isset($this->path['port'])){
$this->port = $this->path['port'];
}
$commonHeader = array('Host: '.$this->path['host'].':'.$this->port);
return array_merge($commonHeader,$header);
}
//GET请求
public function get()
{
$this->method = 'GET';
$this->lineAndHeader = array_merge($this->setLine(),$this->setHeader(),array(''),array(''));
}
//POST请求
public function post($data)
{
$this->method='POST';
$this->lineAndHeader = array_merge($this->setLine(),$this->setHeader(array('Content-type: application/x-www-form-urlencoded','Content-length: '.strlen($data))),array(''),array($data));
}
//发送请求
public function request()
{
$str = implode("\r\n",$this->lineAndHeader);
//echo $str;exit;
$fp = fsockopen($this->path['host'],$this->port,$errno,$errstr,60);
fwrite($fp, $str,strlen($str));
$res = '';
while(!feof($fp)){
$res .= fgets($fp, 512);
}
fclose($fp);
return $res;
}
}
PHP fsockopen模拟发送post set请求
最新推荐文章于 2022-01-16 15:14:36 发布