php curl 传输多维文件数组

<?php

$url = 'http://test.com/index2.php';
$data = [
    'name'       => 'join',
    'files[one]' => getFormFile($filePath, $filePath, 'image/jpeg'),
    'files[two]' => getFormFile($filePath, $filePath, 'image/jpeg'),
];

$result = HttpPie::post($url, 60)->file($data)->send();










/  以下只是工具类 ///










/**
 * 根据文件名获取文件资源,用于向另外一个API提供类似于 input.file 的文件资源
 * @param string $filename 文件名
 * @param string $tmpFile 文件临时路劲
 * @param string $type 文件类型
 * @return mixed
 */
function getFormFile($filename, $tmpFile, $type = 'text/plain')
{
    //php 5.5以上的用法
    if (class_exists('\CURLFile')) {
        $file = new \CURLFile(realpath($tmpFile), $type, $filename);
    } else {
        //5.5以下会走到这步
        $file = '@' . realpath($tmpFile) . ";type=" . $type . ";filename=" . $filename;
    }
    return $file;
}

<?php
/**
 * Author: Tony Chen
 */

namespace common\helpers\transports;

use CURLFile;
use RuntimeException;
use function json_encode;
use function strlen;

/**
 * @author  Tony Chen
 * Class HttpIe
 * <code>
 *   $submit = HttpPie::post($requestUrl)
 *                           ->form($param);
 *   $ret = $submit->getJson();
 * </code>
 * @package app\common\utils
 */
class HttpPie
{
    // 提交类型
    const POST_TYPE_FILE = 'FILE'; // 文件
    const POST_TYPE_JSON = 'JSON'; // json
    const POST_TYPE_FORM = 'FORM'; // form表单

    private $method = 'GET';
    private $url = '';
    private $headers = [];
    private $body = '';
    private $curlOpts = [];
    private $timeout = 3; // 超时时间,默认3秒

    public function __construct()
    {
        if (!extension_loaded('curl')) {
            throw new RuntimeException("Please, install curl extension.\n" . "https://goo.gl/yTAeZh");
        }
    }

    /**
     * @param string $url
     * @param int $timeout 超时时间,默认是3秒
     * @return HttpPie
     * @throws RuntimeException
     */
    public static function get($url, int $timeout = 3): self
    {
        $http = new self();
        $http->method = 'GET';
        $http->url = $url;
        $http->timeout = $timeout;
        return $http;
    }

    /**
     * @param string $url
     * @param int $timeout 超时时间,默认是3秒
     * @return HttpPie
     * @throws RuntimeException
     */
    public static function post($url, int $timeout = 3): self
    {
        $http = new self();
        $http->method = 'POST';
        $http->url = $url;
        $http->timeout = $timeout;
        return $http;
    }

    /**
     * @param array $params
     * @return HttpPie
     */
    public function query(array $params): self
    {
        $http = $this;
        $http->url .= '?' . http_build_query($params);
        return $http;
    }

    /**
     * @param string $header
     * @return HttpPie
     */
    public function header($header): self
    {
        $http = $this;
        $http->headers[] = $header;
        return $http;
    }

    /**
     * json形式传输
     * @param array $data
     * @return HttpPie
     */
    public function body(array $data): self
    {
        $http = $this;
        $http->body = json_encode($data, JSON_PRETTY_PRINT);
        $http->headers += [
            'Content-Type: application/json',
            'Content-Length: ' . strlen($http->body)
        ];
        return $http;
    }

    /**
     * 配合CurlFile传输文件
     * @param array $data = ['file'=>new CURLFile(__DIR__.'/test.png', 'image/png', 'test_name')]
     * @return HttpPie
     */
    public function file(array $data): self
    {
        $http = $this;
        $http->body = $data;
        $http->headers += [
            'Content-Type: multipart/form-data'
        ];
        return $http;
    }

    /**
     * 原始form形式
     * @param array $data
     * @return HttpPie
     */
    public function form(array $data): self
    {
        $http = $this;
        $http->body = http_build_query($data);
        $http->headers += [
            'Content-type: application/x-www-form-urlencoded',
            'Content-Length: ' . strlen($http->body)
        ];
        return $http;
    }

    public function setOpt($key, $value): self
    {
        $http = $this;
        $http->curlOpts[$key] = $value;
        return $http;
    }

    public function send()
    {
//        var_dump($this->body);die;
        $ch = curl_init($this->url);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $this->method);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $this->headers);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $this->body);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch, CURLOPT_MAXREDIRS, 10);
        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, $this->timeout + 3);
        curl_setopt($ch, CURLOPT_TIMEOUT, $this->timeout);

        foreach ($this->curlOpts as $key => $value) {
            curl_setopt($ch, $key, $value);
        }

        //TODO:关闭证书校验
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);

        $result = curl_exec($ch);
        if ($result === false) {
            throw new RuntimeException('curl errno: ' . curl_errno($ch) . ' error_msg: ' . curl_error($ch));
        }

        $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        // 404/502等非200的状态码,直接抛异常出去
        // msg就是html的整个内容结构
        if ($httpCode !== 200) {
            throw new RuntimeException($result);
        }
        curl_close($ch);
        return $result;
    }

    public function getJson()
    {
        $result = $this->send();
        $response = json_decode($result, true);
        if (json_last_error() !== JSON_ERROR_NONE) {
            throw new RuntimeException('JSON Error: ' . json_last_error_msg() . ' content: ' . $response);
        }
        return $response;
    }
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值