写入网页地址,调用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();
?>