首先本文使用之前的一个留言板案例进行测试,案例连接:使用POST实现对留言板的留言。前面部分是关于步骤原理的讲解,后半部分是继续上一篇文章的代码实现。那么现在开始:
1. 留言页面如下:
先提交一个留言,然后抓包查看POST数据。
看见了这句话:
<span style="font-family:KaiTi_GB2312;font-size:14px;">title=vEagleFly&author=vEagleFly&content=vEagleFly</span>
这就是我们提交的数据。
所以,接下来我们就要开始仿照实现了。其实这里我们之前也遇到过,就是这篇文章,HTTP应用模拟灌水机器人,道理是一样的。只不过我们换种方法,类实现它。
查看留言,实现成功!
【代码实现】:
<span style="font-family:KaiTi_GB2312;"><?PHP
/*
PHP + Socket编程 发送HTTP请求
*/
//http请求类的接口
interface Proto{
//连接url
function conn($url);
//发送get查询
function get();
//发送post查询
function post();
//关闭连接
function close();
}
class Httpimplements Proto{
//定义一个回车换行,在Linux下是'\n' 在windows下是'\r\n'
//HTTP标准是'\r\n'
const CRLF = "\r\n";
protected $errno = -1;
protected $errstr = '';
protected $response = '';
protected $url = null;
protected $fh = null;
protected $version = 'HTTP/1.1';
protected $line = array();
protected $header = array();
protected $body = array();
public function __construct($url){
$this -> conn($url);
$this -> setHeader('Host: '.$this ->url['host']);
}
//此方法负责写请求行
protected function setLine($method){
$this -> line[0] = $method.''.$this->url['path'].' '.$this->version;
}
//此方法负责写头信息
protected function setHeader($headerline){
$this -> header[] = $headerline;
}
//此方法负责写主体信息
protected function setBody($body){
$this -> body[] =http_build_query($body);
}
//连接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,3);
}
//构造get请求数据
public function get(){
$this -> setLine('GET');
$this -> request();
}
//构造post请求数据
public function post($body = array()){
$this -> setLine('POST');
$this -> setBody($body);
$this -> setHeader('Content-length:'.strlen($this->body[0]));
$this-> setHeader('Content-type: application/x-www-form-urlencoded');
$this -> request();
}
//发送GET请求
public function request(){
//把请求行,头信息,实体信息放在一个数组里,便于拼接。
$req = array_merge($this -> line,$this-> header,array(''),$this -> body,array(''));
$req = implode(self::CRLF,$req);
// echo $req;
fwrite($this->fh,$req);
while(!feof($this->fh)){
$this -> response .=fread($this->fh,1024);
}
echo $this -> response;
$this -> close();//关闭连接
}
//关闭连接
public function close(){
$fclose($this -> fh);
}
}
/*$url ='http://localhost/test.php';
$http = newHttp($url);
$http -> get();
*/
$url ='http://127.0.0.1/liuyan/doAdd.php ';
$post = newHttp($url);
$post ->post(array('title'=>'ceshi','author'=>'vEagleFly','content' => 'no'));
</span>
【运行结果】:
至此,使用Socket编程实现GET和POST发送请求数据已经全部实现完毕。
【知识拓展】:
若要实现批量发帖(也就是灌水),加一个for循环即可。
<span style="font-family:KaiTi_GB2312;font-size:14px;">set_time_limit(0);
$url ='http://127.0.0.1/liuyan/doAdd.php ';
for($i = 0; $i <10; $i ++){
$post = new Http($url);
$post ->post(array('title'=>'guanshui','author'=>'vEagleFly','content' =>'haha'));
usleep(20000);//延迟2s发送,太快自己机器不能承受。
}</span>