<?php /* 模拟发送GET和POST */ class HttpFsockopen{ const EOF = "\r\n"; private $errno = -1; private $error = ''; private $respons = ''; private $url = array(); private $line = array(); private $header = array(); private $body = array(); private $ver = 'HTTP/1.1'; //http协议 private $fh = null; public function __construct($url){ $this->conn($url); $this->setHeader('Host: '.$this->url['host']); } //设置写请求行 private function setLine($method){ $this->line[0] = $method. ' '.$this->url['path'].'?'.$this->url['query'].' '.$this->ver; } //设置写头信息 public function setHeader($header){ $this->header[] = $header; } //设置写主体信息 private function setBody($body=array()){ $this->body[] = http_build_query($body); } //连接URL private 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->error,5); } //构造GET请求 public function get(){ $this->setLine('GET'); $this->request(); return $this->respons; } //构造POST请求 public function post($body=array()){ $this->setLine('POST'); # content-type $this->setHeader('Content-type:application/x-www-form-urlencoded'); # 构造主体信息 $this->setBody($body); # content-length $this->setHeader('content-length:'.strlen($this->body[0])); return $this->request(); } //请求 private function request(){ //把请求行头信息,实体信息,放在一个数组里,便于拼接 $req = array_merge($this->line,$this->header,array(''),$this->body,array('')); $req = implode(self::EOF, $req); fwrite($this->fh, $req); while(!feof($this->fh)){ $this->respons .= fread($this->fh,1024); } $this->close(); //关闭连接 return $this->respons; } //关闭连接 private function close(){ fclose($this->fh); } } $url = 'http://sports.sina.com.cn/nba/2013-08-28/07206745076.shtml'; $http = new HttpFsockopen($url);
$http->setHeader('Connection:close');//请求完成关闭连接,提高速度 echo $http->get(); /* <? $fp = fsockopen ("en.tanbo.name", 80, $errno, $errstr, 30); if (!$fp) { echo "$errstr ($errno) "; } else { $msg="GET /getip.php HTTP/1.0 "; $msg.="Host:en.tanbo.name "; $msg.="Referer: http://en.tanbo.name/getip.php "; $msg.="Client-IP: 202.101.201.11 "; $msg.="X-Forwarded-For: 202.101.201.11 "; //主要是这里来构造IP $msg.="Connection: Close "; fputs ($fp, $msg); while (!feof($fp)) { echo fgets ($fp,1024); } fclose ($fp); } ?> */ ?>