当前位置 : 主页 > 网络编程 > PHP >

PHP Post And Get Class

来源:互联网 收集:自由互联 发布时间:2021-06-28
封装PHP cUrl库。主要提供post、get方法,支持cookie,session curl = curl_init();$this-setopt(CURLOPT_RETURNTRANSFER, true);$this-setopt(CURLOPT_HEADER, true);$this-setopt(CURLOPT_FOLLOWLOCATION, true);}public function post($url
封装PHP cUrl库。主要提供post、get方法,支持cookie,session
 curl = curl_init();
		$this->setopt(CURLOPT_RETURNTRANSFER, true);
		$this->setopt(CURLOPT_HEADER, true);
		$this->setopt(CURLOPT_FOLLOWLOCATION, true);
	}
	
	public function post($url, $data, $cookie = '', &$session = false, &$code = false){
		$this->setopt(CURLOPT_URL, $url);
		$this->setopt(CURLOPT_POST, true);
		$this->setopt(CURLOPT_POSTFIELDS, $data);
		$this->setopt(CURLOPT_COOKIE, $cookie);

		$out = $this->exec();
		$arr = $this->cutHeadAndBody($out);
		$code = $this->getStart($arr['head']);
		$session = $this->getCookie($arr['head']);
		return $arr['body'];
	}
	
	public function get($url, $cookie = '', &$session = false, &$code = false){
		$this->setopt(CURLOPT_URL, $url);
		$this->setopt(CURLOPT_POST, false);
		$this->setopt(CURLOPT_COOKIE, $cookie);
	
		$out = $this->exec();
		$arr = $this->cutHeadAndBody($out);
		$code = $this->getStart($arr['head']);
		$session = $this->getCookie($arr['head']);
		return  $arr['body'];
	}
	
	public function setopt($key, $value){
		curl_setopt($this->curl, $key, $value);
	}
	
	public function exec(){
		return curl_exec($this->curl);
	}
	
	function  __destruct(){
		curl_close($this->curl);
	}
	
	//分割出返回头和html主体
	private function cutHeadAndBody($content){
		$arr = explode($this->HTML,$content,2);
		$newArray = ['head'=>$arr[0],'body'=>$arr[0]];
		if(count($arr) > 1) $newArray['body'] = $this->HTML.$arr[1];
		return $newArray;
	}
	
	//取出200状态码,除200外其他状态码可能取不出,待优化
	private function getStart($head){
		$arr = explode("\n", $head);
		$newCode = false;
		foreach($arr as $list){
			if(preg_match('/^HTTP.*\ ([0-9]*)\ OK/i', $list, $code) > 0){
				$newCode = $code[1];
			}
		}
		return $newCode;
	}
	
	//取出返回的cookie
	private function getCookie($head){
		$cookie = '';
		$preg = '/^set\-cookie:([^\r\n]*)/im';
		$num = preg_match_all($preg, $head, $out);
		foreach($out[1] as $list){
			$cookie .= $list.';' ;
		}
		return $cookie;
	}
	
	
}
网友评论