php利用socket发请求

<?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);





  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值