PHP fsockopen模擬發送post set請求

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;
	}
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章