php Curl链式写法模拟表单提交

最近在看书的时候,书中的作者有讲到用php来实现链式写法,顿时让我感到很惊奇。这让我想起来了TP框架的链式写法:

Db(xxx)->where(xxx)->select();

然后通过在网上查阅了一些资料大致了解了它的实现原理:其实和我们平常写的class类没用区别,唯一有区别的就是要在每个方法里面返回当前对象给下一个方法继续调用,如return $this。基于此封装了一个简单的curl模拟post、get、上传文件的类方法。因为平常会用php写一些接口,自己用很方便。

<?php
/*
 * Curl 模拟表单提交
 */
class CurlUploadFile{

	/**
	 * @var $filepath 上传文件本地路径
	 * @var $address 上传地址
	 */
	protected $filepath;
	protected $address;
	
	/**
	 * @param String $url 需要模拟提交的地址
	 */
    public function url(string $url)
    {
    	if(!$url){
    		throw new Exception('上传地址不存在');
    	}
    	$this->address = $url;
    	return $this;
    }

    /**
     * @param String $path 文件路径 
     */
	public function path(string $path)
	{
		if(file_exists($path)){
			$this->filepath = $path;
			return $this;
		}
		throw new Exception('文件路径不存在');
	}

	/**
	 * @param Array $param 自定义参数 
	 */
	public function post(Array $param)
	{   

		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $this->address);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch,CURLOPT_POST,1);
		$param = $param;
	    if($this->filepath){
	    	$param += $this->up_handle($ch);
	    }	
		curl_setopt($ch, CURLOPT_POSTFIELDS, $param);
		//curl_setopt($ch, CURLOPT_HEADER,1);
		$request = curl_exec($ch);
		curl_close($ch);
		return $request;
	}

	/**
	 * @param resource $ch curl初始句柄文件
	 * 
	 */
	protected function up_handle($ch)
	{
		$data = [];
		if(class_exists('\CURLFile')) //这里做一下兼容处理,php5.6以后不允许使用@上传文件,官方的说法是为了安全因为@这个符号在php里也可以抑制错误
		{  
			curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true);
			$data = ['file' => new \CURLFile(realpath($this->filepath))];
		}
		else
		{
			if(defined('CURLOPT_SAFE_UPLOAD'))
			{
				curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false);
			}
			$data = ['file' => "@{$this->filepath}"];
		}
		return $data;
	}

	/**
	 * @param Array $param 自定义参数
	 */
	public function get(Array $param)
	{
		$ch = curl_init();
		$param = http_build_query($param);
		$address = rtrim($this->address,'?') . '?' . $param;
		curl_setopt($ch,CURLOPT_URL,$address);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch,CURLOPT_HEADER,1);
		$request = curl_exec($ch);
		curl_close($ch);
		return $request;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值