标签:
可以根据几根url地址,分析出主机,地址,协议等,然后用封装成的类拼接成GET请求信息,用fsockopen连接主机,进行读取操作,获取响应信息,打印
<?php //http连接接口 interface proto{ //连接url public function conn($url); //发送get请求 public function get(); //发送post public function post($num); //关闭连接 public function close(); } class Http implements proto{ const CRLF="\r\n"; protected $response=‘‘; protected $poststr=‘‘; protected $errno=-1; protected $errstr=‘‘; protected $version=‘HTTP/1.1‘; protected $fh=null; protected $url=array(); protected $line=array(); protected $header=array(); protected $body=array(); public function __construct($url){ $this->conn($url); $this->setheader(); } //负责写请求行 protected function setLine($method){ $this->line[0]=$method .‘ ‘.$this->url[‘path‘] .‘ ‘.$this->version; } //负责写请求信息 protected function setHeader(){ $this->header[]=‘Host:‘.$this->url[‘host‘]; } //负责写主题信息 protected function setBody(){ } //连接url public function conn($url){ $this->url=parse_url($url); //判断端口 if(!isset($this->url[‘port‘])){ $this->url[‘port‘]=80; } $this->fh=fsockopen($this->url[‘host‘],$this->url[‘port‘],$this->errno,$this->errstr,3); } //构造get请求数据 public function get(){ $this->setLine(‘GET‘); $this->request(); return $this->response; } //构造post请求数据 public function post($num){ $this->setLine(‘POST‘); $this->header[]=‘content-length:‘.$num; $this->header[]=‘content-type:application/x-www-form-urlencoded‘; // print_r($this->header); } //添加postti提交的信息 public function postStr($str){ $this->poststr=$str; } //真正的请求 public function request(){ $req=array_merge($this->line,$this->header,array(‘‘),$this->body,array(‘‘));//拼接请求信息为数组 // print_r($req); $req=implode(self::CRLF,$req); // echo $req; fwrite($this->fh,$req); while(!feof($this->fh)){ $this->response.=fread($this->fh,1024); } $this->close(); } //关闭连接 public function close(){ fclose($this->fh); } } //调试 $url=‘http://bbs.chinaunix.net/zhuanti/1041/httpyoujizhongqingqiu_1041558.shtml‘; $http=new Http($url); echo $http->get(); // print_r($http); ?>
标签:
原文地址:http://www.cnblogs.com/lzzhuany/p/4842159.html