<?php
/**
PHP+scoket编程 发送HTTP请求
功能:批量发帖(无登录注册)
**/
//http请求类接口
interface Prote{
//连接url
function conn($url);
//发送get查询
function get();
//发送post查询
function post();
//关闭连接
function close();
}
class Http implements Prote{
const CRLF = "\r\n"; //声明一个换行常量
protected $errno = -1;
protected $errstr = '';
protected $response = '';
protected $fh = null;
protected $url = array(); //存放url信息
protected $line = array(); //放置请求行
protected $header = array(); //放置头信息
protected $body = array(); //放置主体信息
public function __construct($url){
$this->conn($url);
$this->setHeader('Host:' . $this->url['host']);
}
/**
* [setLine 此方法负责写请求行]
* @param [str] $method [description]
*/
protected function setLine($method){
$this->line[0] = $method . ' ' .$this->url['path'] . ' ' . 'HTTP/1.1';
}
/**
* [setHeader 此方法负责写头信息]
* @param [type] $headerline [头信息]
*/
protected function setHeader($headerline){
$this->header[] = $headerline;
}
//此方法负责写主体信息
protected function setBody($body){
$this->body[] = http_build_query($body);
}
/**
* [conn 连接url]
* @param [type] $url [请求的地址]
* @return [type] [description]
*/
public function conn($url){
$this->url = parse_url($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 构造get请求的数据]
* @return [type] [description]
*/
public function get(){
$this->setLine('GET');
$this->request();
return $this->response;
}
/**
* [post 构造post查询的数据]
* @return [type] [description]
*/
public function post($body = array()){
$this->setLine('POST');
// 设置content-type
$this->setHeader('Content-type:application/x-www-form-urlencoded');
//构造主体信息 ,比GET不一样的地方
$this->setBody($body);
//计算content-length
$this->setHeader('Content-length: ' . strlen($this->body[0]));
$this->request();
}
/**
* [request 真正请求]
* @return [type] [description]
*/
public function request(){
//把请求行、头信息、实体信息 放在一个数组中,便于拼接
$req = array_merge($this->line,$this->header,array(''),$this->body,array(''));
$req = implode(self::CRLF,$req);
/**
* 请求信息拼接结果
* GET /17/0223/08/CDUQ91V100097U7T.html HTTP/1.1
* Host: tech.163.com
*
*
*/
echo $req;
fwrite($this->fh,$req);
while(!feof($this->fh)){
$this->response .= fread($this->fh,1024);
}
$this->close(); //关闭连接
}
/**
* 换行:
* linux:\r
* mac : \n
* window : \r\n
* http标准协议:\r\n
*/
//关闭连接
public function close(){
fclose($this->fh);
}
}
set_time_limit(0);
$url = "http://mywishingwall.com/";
for($i=1;$i<100;$i++){
$str = str_shuffle('abcdefghijklmnopqrst01223456789');
$user = substr($str,0,5);
$content = substr($str,6,8);
$http = new Http($url);
echo $http->post(array('username'=>$user,'content'=>$content));
echo $user . '<br/>' . $content;
usleep(20000);
}