<?php
//设置php运行时间
set_time_limit(0);
interface Item{
//链接url
public function conn($url);
//get请求
public function get();
//post请求
public function post();
// 关闭连接
public function close();
}
class Socket implements Item{
const CRLF = "\r\n";
protected $errno = -1;
protected $error = '';
protected $response = '';
protected $url = null;
protected $version = 'HTTP/1.1';
protected $fh = null;
protected $line = array();
protected $header = array();
protected $body = array();
public function __construct($url){
$this -> conn($url);
$this -> header('Host: ' . $this->url['host']);
}
//链接url
public function conn($url){
//分析url
$this -> url = parse_url($url);
//看看有没有其他的端口号
if(!isset($this-> url['port'])){
$this-> url['port'] = 80;
}
$fh = $this -> url;
$this -> fh = fsockopen($fh['host'],$fh['port'],$this->errno,$this->error,5);
}
//写头信息
public function header($header){
$this -> header[] = $header;
}
//写请求行信息
public function line($method){
$this -> line[0] = $method . ' ' . $this->url['path'] . ' '. $this-> version;
}
//请求主体信息
public function body($body){
$this -> body[] = http_build_query($body);
}
//构造get请求
public function get(){
//行信息
$this -> line('GET');
//读写操作
$this -> request();
//返回页面
return $this -> response;
}
//post请求
public function post($body = []){
//行信息
$this -> line('POST');
//设置表单提交的数据格式
$this -> header('Content-type: application/x-www-form-urlencoded');
//设置提交的主体信息
$this -> body($body);
//计算主体提交的长度
$this -> header('Content-length: '. strlen($this -> body[0]));
//读写操作
$this -> request();
}
//真正的请求
public function request(){
//把请求行 请求头 主体信息 拼起来放置到一个数组中,便于操作
$res = array_merge($this -> line , $this -> header , [''] , $this -> body , [''] );
//进行数组分割
$res = implode(self::CRLF,$res);
//进行文件写入
fwrite($this -> fh , $res);
//进行读文件
while(!feof($this -> fh)){
$this -> response .= fread($this -> fh , 2048);
}
//关闭连接
$this -> close();
}
//进行资源关闭
public function close(){
fclose($this -> fh);
}
}
/*get请求*/
$url = 'http://www.zixue.it/thread-10101-1-1.html';
$socket = new Socket($url);
echo $socket -> get();
/*post请求*/
$url = 'http://127.0.0.1/http/01.php';
$name = 'ad;dd;f';
$pwd = 'hhe';
$socket = new Socket($url);
$data = ['name'=>$name,'pwd'=>$pwd];
$socket -> post($data);
php利用socket发请求
最新推荐文章于 2024-09-16 22:19:19 发布