七牛云 PHP SDK历史文档
SDK源码地址
1、开通七牛开发者帐号
2、登录七牛开发者自助平台,查看 Access Key 和 Secret Key
require_once "./php-sdk-7.2.10/autoload.php"; // 引入下载好的SDK
use Qiniu\Auth; // 引入鉴权类
use Qiniu\Storage\UploadManager; // 引入上传类
$accessKey = '你的accessKey';
$secretKey = '你的secretKey';
$bucket='你的空间名称';
$expires = 6000;
// 初始化签权对象
$auth = new Auth($accessKey, $secretKey);
$policy = array(
'callbackBody' => 'key=$(key)&hash=$(etag)&bucket=$(bucket)&fsize=$(fsize)&name=$(x:name)',
'callbackBodyType' => 'application/json'
);
$token = $auth->uploadToken($bucket, null, $expires, $policy, true);
// 构建 UploadManager 对象
$uploadMgr = new UploadManager();
// 要上传文件的本地路径
$filePath = $_FILES['file']['tmp_name'];
//图片文件的生成
$savename = date('YmdHis',time()).mt_rand(0,9999);
$file_type = $_FILES["file"]["type"];
$type = '';
switch ($file_type) {
case 'image/png':
$type = '.png';
break;
case 'image/gif':
$type = '.gif';
break;
case 'image/jpeg':
$type = '.jpg';
break;
}
// 上传到七牛后保存的文件名
$name = $savename.$type;
list($ret, $err) = $uploadMgr->putFile($token, $name, $filePath);
$path = "http://q7ydbxkf6.bkt.clouddn.com/".$savename.$type; // http://q7ydbxkf6.bkt.clouddn.com 你的七牛云外链域名
if ($err !== null) {
$data["code"] = 500;
$data["msg"] = '上传失败';
$data["errno"] = $_FILES["file"]["error"];
echo json_encode($data);
} else {
$data["code"] = 200;
$data["msg"] = '上传成功';
$data["errno"] = $_FILES["file"]["error"];
$data['data'] = $name;
$data['path'] = $path;
echo json_encode($data);
}