腾讯云CSF文件对象存储的php示例


thinkphp 6自带上传拓展,当然也可以上云,以下是腾讯云的Cloud File Storage,简称CFS。

需要替换CfsLogic的静态成员变量的SECRET_ID/SECRET_KEY/APP_ID/BUCKET_NAME即可。

<?php
declare (strict_types=1);

namespace app\common\logic;


/**
 * 文件存储(Cloud File Storage,CFS)
 */
class CfsLogic
{
    const _secretId = SECRET_ID;
    const _secretKey = SECRET_KEY;
    const _appid = APP_ID;
    const _bucket = BUCKET_NAME;
    const _host = "sts.api.qcloud.com/v2/index.php";

    protected $params = [];
    protected $policy = '';
    protected $method = 'GET';

    public function __construct($bucket, $region = '')
    {
        $this->policy = '{
            "version": "2.0",
            "statement": [{
                "action": [
                    "name/cos:*"
                ],
                "effect": "allow",
                "principal": {"qcs": ["*"]},
                "resource": [
                "qcs::cos:ap-guangzhou:uid/' . self::_appid . ':prefix//' . self::_appid . '/' . self::_bucket . '",
                "qcs::cos:ap-guangzhou:uid/' . self::_appid . ':prefix//' . self::_appid . '/' . self::_bucket . '/*"
                ]
            }]
         }';

        $this->params = array(
            "Action" => "GetFederationToken",
            "SecretId" => self::_secretId,
            "Region" => "ap-guangzhou",
            "Timestamp" => time(),
            "Nonce" => mt_rand(),
            "name" => "",
            "durationSeconds" => 300,
            "policy" => $this->policy,
            "Signature" => "",
        );

    }

    public function execute()
    {

        //生成拼接签名源文字符串 makeSignPlainText
        $url = self::_host . '';//url路径
        // 取出所有的参数
        $paramStr = $this->buildParam($this->params, $this->method);
        $plainText = $this->method . $url . $paramStr;
        $this->params['Signature'] = $this->sign($plainText);

        $result = $this->post("https://" . self::_host, $this->params);
        $arr = json_decode($result, true);//dumps($arr);exit;
        if ($arr['code'] != 0){
            $error = self::class . ':' . $result;
            dumps($error,'error');
            throw new \Exception($error);
        }
        return $arr['data'];
    }


    /**
     * sign
     * 生成签名
     * @param string $srcStr 拼接签名源文字符串
     * @param string $method 请求方法
     * @return
     */
    private function sign($srcStr, $method = 'HmacSHA1')
    {
        switch ($method) {
            case 'HmacSHA1':
                $retStr = base64_encode(hash_hmac('sha1', $srcStr, self::_secretKey, true));
                break;
            case 'HmacSHA256':
                $retStr = base64_encode(hash_hmac('sha256', $srcStr, self::_secretKey, true));
                break;
            default:
                throw new Exception($method . ' is not a supported encrypt method');
                return false;
                break;
        }
        return $retStr;
    }

    /**
     *
     * 拼接参数 buildParam
     * @param array $requestParams 请求参数
     * @param string $requestMethod 请求方法
     * @return
     */
    protected function buildParam($requestParams, $requestMethod = 'GET')
    {
        $paramStr = '';
        ksort($requestParams);
        $i = 0;
        foreach ($requestParams as $key => $value) {
            if ($key == 'Signature') {
                continue;
            }
            // 排除上传文件的参数
            if ($requestMethod == 'POST' && substr($value, 0, 1) == '@') {
                continue;
            }
            // 把 参数中的 _ 替换成 .
            if (strpos($key, '_')) {
                $key = str_replace('_', '.', $key);
            }
            if ($i == 0) {
                $paramStr .= '?';
            } else {
                $paramStr .= '&';
            }
            $paramStr .= $key . '=' . $value;
            ++$i;
        }
        return $paramStr;
    }


    protected function post($url, $param)
    {
        //初始化
        $curl = curl_init();
        //设置抓取的url
        $URL = $url . "?" . http_build_query($param);
        curl_setopt($curl, CURLOPT_URL, $URL);
        //设置头文件的信息作为数据流输出
        //curl_setopt($curl, CURLOPT_HEADER, 1);
        //设置获取的信息以文件流的形式返回,而不是直接输出。
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
        //执行命令
        $data = curl_exec($curl);
        //echo curl_getinfo($curl,CURLINFO_HTTP_CODE); //输出请求状态码
        //关闭URL请求
        curl_close($curl);
        //显示获得的数据
        return $data;
    }
}

原文链接:https://blog.yongit.com/note/762471.html