利用 socket 发送 get/post 请求

时间:2022-03-22 10:12:35

思路:利用 fsockopen 函数与要请求的主机建立一个通信通道,再将请求行、头信息、主体信息通过这个通道传输给主机实现请求的发送。利用这种方式发送 get 请求就是常说的小偷程序,发送 post 请求则可以在论坛、博客发帖。

代码:

<?php
/*利用HTTP协议socket发送get请求(小偷程序)、post请求(批量发帖程序)
* 知识点:fsockopen、parse_url
*/
//请求类的接口
header('content-type:text/html;charset=utf-8');
interface Proto{
function request($url);
function get();//
function post($str);
function close();//关闭连接
} class Http implements Proto{ protected $url = array();
protected $header = null;
protected $method = null;
protected $port = null;
protected $response = null;
protected $errno = -1;
protected $errstr = null;
protected $str = null;
public function _construct($url){ } public function setheader(){
$this->header = $this->method.' '.$this->url['path'].' HTTP/1.1';//记录请求行
$this->header .= "\r\nHost: ".$this->url['host'];//记录头信息
$this->header .= "\r\nReferer: ".$this->url['host'];//伪造referer信息
if($this->method=='GET'){
$this->header .= "\r\n\r\n";
}
if($this->method=='POST'){//记录主体信息
$this->header .="\r\nContent-type: application/x-www-form-urlencoded";
$this->header .="\r\nContent-length: ".strlen($this->str);
$this->header .="\r\n\r\n" . $this->str;
}
} public function request($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);
$this->setheader();
fwrite($this->fh,$this->header);//将请求行、头信息、主体信息通过通道传给主机
while(!feof($this->fh)){
$this->response .= fread($this->fh,10240);
}
$this->close();
return $this->response;
} function get(){
$this->method = "GET";
}
function post($str){
$this->method = "POST";
$this->str = $str;
}
function close(){
fclose($this->fh);
}
}
/*发送get请求
$url='http://mobile.163.com/16/0518/07/BNB519NG0011179O.html#index_digi_1';
$ht = new Http();
$ht->get();
echo $ht->request($url);
*/ /*发送post请求*/
$url='http://localhost:81/web/message/index.php';
$str='user=老李&title=测试HTTP&content=这是个测试&submit=提 交';
$ht = new Http();
$ht->post($str);
echo $ht->request($url); /*盗链图片
$url='http://........png';
$ht = new Http();
$ht->get();
$p = substr(strstr($ht->request($url),"\r\n\r\n"),4);
file_put_contents('./aa.png',$p);
*/
?>

如果发送请求的页面需要登录,只需在头信息中增加 “cookie: .....” 就可以了,cookie后面的信息可以通过抓包查看。