<?php interface Proto { // 鏈接 function conn($url); // 發送get請求 function get(); // 發送post查詢 function post($data); // 關閉鏈接 function close(); } class Http implements Proto { const CRLF = "\r\n"; // 行分隔符 protected $url = null; // url地址 protected $errno = -1; // 錯誤號 protected $errstr = ''; // 錯誤信息 protected $response = ''; // 返回信息 protected $version = 'HTTP/1.1'; // HTTP協議版本 protected $fh = null; // 打開遠程文件的資源 protected $line = array(); // 消息行 protected $header = array(); // 請求頭 protected $body = array(); // 實體信息 protected $expires_time = 300; // 鏈接過時時間 public function __construct($url) { $this->conn($url); $this->setHeader("Host: ".$this->url['host']); } // 鏈接 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,$this->expires_time); } // 設置請求行 protected function setLine($method) { $this->url['path'] .= isset($this->url['query']) ? '?'.$this->url['query'] : ''; $this->line[] = $method.' '.$this->url['path'].' '.$this->version; } // 設置頭信息 public function setHeader($header) { $this->header[] = $header; } // 設置實體信息 protected function setBody($data) { $this->body[] = http_build_query($data); // $this->body[0] = $data; } // 發送get請求 public function get() { $this->setLine('GET'); $this->request(); return $this->response; } // 發送post查詢 public function post($data) { $this->setLine('POST'); $this->setHeader("Content-type: application/x-www-form-urlencoded"); $this->setBody($data); $this->setHeader("Content-length: ".strlen($this->body[0])); $this->request(); return $this->response; } // 真正的請求 protected function request() { $req = array_merge($this->line,$this->header,array(''),$this->body,array('')); $req = implode(self::CRLF,$req); echo $req; // exit; // 寫入 fwrite($this->fh,$req); while(!feof($this->fh)){ $this->response .= fread($this->fh,1024); } $this->close(); } // 關閉鏈接 public function close() { fclose($this->fh); } } // $url = 'http://shunping.com/msg.php'; // $url = 'http://news.163.com/13/0613/09/9187CJ4C00014JB6.html'; // $http = new Http($url); // echo $http->get(); // tit=test&con=tset&submit=%E6%8F%90%E4%BA%A4 // $data['tit'] = 'test'; // $data['con'] = 'tset'; // $data['submit'] = '%E6%8F%90%E4%BA%A4'; // $data['submit'] = '提交'; // echo $http->post($data); ?>