http--發送get請求獲取網頁


寫入網頁地址,調用get方法,獲得響應


<?php
/*php+socket編程 發送http
http類 操作案例get--獲取網頁 post批量發帖 */

// 類似fopen,fwrite輸入內容進txt文件
interface Proto{
	//連接
	function conn($url);

	//發送get
	function get();

	//發送post
	function post();

	//關閉
	function close();

}


//* 繼承的東西全要繼承不能不寫
class Http implements Proto{
	protected $url=null;
	protected $line=array();
	protected $header=array();
	protected $body=array();

	protected $fh=NULL;
	protected $version="HTTP/1.1";
	protected $errno= -1;
	protected $errstr='';
	protected $resp='';//響應
	const CRLF="\r\n";


	//* 一開始就需要的變量 填在construct裏
	public function __construct($url){
		$this->conn($url);
		$this->setHeader();//本來寫在get方法,但所有請求方法header相同
	}

	//連接,得到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,10);
	// resource fsockopen ( string $hostname [, int $port = -1 [,
	 // int &$errno [, string &$errstr [, float $timeout 
	 // = ini_get("default_socket_timeout") ]]]] )
	// 初始化一個套接字連接到指定主機(hostname)。也就是打開了通道可以讀取寫入進這個網站
	}


	//發送get *怎麼get寫在$line前面 setline方法設一個變量,在不同請求方法裏用
	public function get(){
		$this->setLine('GET');
		$this->request();
		return $this->resp;
	}

	//發送post
	public function post(){

	}

	// 請求拼接發送 *怎麼整合 請求數組變成str
	public function request(){
		$req=array_merge($this->line,$this->header,array(''),$this->body,array(''));
		$req=implode(self::CRLF, $req);//crlf換行
		// echo $req;
		// 寫入請求*
		fwrite($this->fh, $req);
		while (!feof($this->fh)) {
			$this->resp.=fread($this->fh, 1024);
		}
		// $this->close();

	}

	//關閉
	public function close(){

	}

	// 拼接 請求行1
	protected function setLine($method){
		$this->line[]=$method." ".$this->url['path']." ".$this->version;

	}

	//請求頭部2
	protected function setHeader(){
		$this->header[]="Host:".$this->url['host'];

	}


	//請求主體部分3
	protected function setBody(){

	}

}


$http=new Http('http://news.qq.com/a/20160107/019440.htm');
// url====[scheme] => http [host] => news.163.com [path] => /16/0107/06/BCN66S6S00014AED.html 

echo $http->get();
//line === Array ( [0] => GET /16/0107/06/BCN66S6S00014AED.html HTTP/1.1 ) 
//header === Array ( [0] => Host:news.163.com )
// $http->request();

?>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章