刘明野

[PHP]七牛云 未备案域名 免下载流量 获取文件

可以免备案拉取七牛云的文件,而且还免流量。
七牛云每个区域都有10G免费对象存储,可以存储一些大文件,用PHP拉取。
没有写缓存,加上缓存会更快一些。
注意:私有空间也可以获取。

<?php
/**
 * Created by VScode.
 * User: LiuMingye
 * Date: 20-6-15
 * Time: 下午7:36
 */

function qiniu($file, $bucket)
{
    // 公钥私钥
    $access_key = "在这里输入七牛云的access_key";
    $secret_key = "在这里输入七牛云的secret_key";
    // 获取文件名
    $name = basename($file);
    // 文件路径编码
    if (substr($file, 0, 1) == "/") {
        $file = substr($file, 1);
    }
    $file = str_replace(['/'], ['!'], $file);
    // 生成Token
    $authorization = hash_hmac('sha1', "/get/!$bucket:$file\n", $secret_key, true);
    $authorization = str_replace(['+', '/'], ['-', '_'], base64_encode($authorization)); // URL安全 Base64编码
    $authorization = "QBox $access_key:$authorization";
    // get
    $curl = curl_init(); // 启动一个CURL会话
    curl_setopt($curl, CURLOPT_HTTPHEADER, ["Authorization: $authorization" ]);
    curl_setopt($curl, CURLOPT_URL, "http://rs.qiniu.com/get/!$bucket:$file");
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
    $data = curl_exec($curl); // 执行操作
    curl_close($curl); // 关闭CURL会话
    $data = json_decode($data, true);
    $url = str_replace('http://', 'https://', $data['url']);
    // 获取下载链接
    if ($url) {
        $url .= "/$name";
        return $url;
        // header("Location: $url");
        exit();
    }
    return false;
    exit();
}
// 示例
echo qiniu('测试文件.zip', '空间名称');
echo qiniu('文件夹/测试文件.zip', '空间名称');
本文为作者刘明野发布,未经允许禁止转载!
3701
1
3
发表留言

    3年前

    个人觉得,七牛云不好用

友情链接