基于PHP实现阿里云开放存储服务
开放存储服务(OpenStorageService,简称OSS),是阿里云对外提供的海量,安全,低成本,高可靠的云存储服务。用户可以通过简单的API(REST方式的接口),在任何时间、任何地点、任何互联网设备上进行数据上传和下载。
首先、登录阿里云首页http://www.aliyun.com/ 免费开通服务。
开通以后,进入"管理控制台"--进入"开发存储服务OSS",进入到控制台。
其次、下载SDK http://bbs.aliyun.com/job.php?action=download&aid=41064
解压后在samples文件夹内新建一个index.php文件
<?php require_once dirname(__DIR__).'/aliyun.php'; use Aliyun\OSS\OSSClient; // 创建一个连接阿里云开放存储的客户端 function createClient($accessKeyId, $accessKeySecret) { return OSSClient::factory(array( 'AccessKeyId' => $accessKeyId, //AccessKeyId在“用户中心”--“我的服务”--“安全认证” 'AccessKeySecret' => $accessKeySecret, )); } //获取所有bucket //bucket是水桶的意思,可以理解为容器,里面装了各种各样的东西,也就是key=>value function listBuckets(OSSClient $client) { $buckets = $client->listBuckets(); foreach ($buckets as $bucket) { echo 'Bucket: ' . $bucket->getName() . "\n"; } } //新建bucket function createBucket(OSSClient $client, $bucket) { $client->createBucket(array( 'Bucket' => $bucket, )); } // Sample of get Bucket Acl function getBucketAcl(OSSClient $client, $bucket) { $acl = $client->getBucketAcl(array( 'Bucket' => $bucket, )); $grants = $acl->getGrants(); echo $grants[0]; } //获取bucket的所有key function getBucketKey(OSSClient $client, $bucket){ $objectListing = $client->listObjects(array( 'Bucket' => $bucket, )); foreach ($objectListing->getObjectSummarys() as $objectSummary) { $objectSummary->getKey(); } } //向某个bucket上传内容,可以字符串或者文件 function upload(OSSClient $client, $bucket,$key,$content,$type){ isset($type)?$type:0; if($type == 0){ $type = gettype($content); //如果上传内容为数组或者对象,需要进行序列化 if($type == "array" || $type == "object") { $content = serialize($content); } $client->putObject(array( 'Bucket' => $bucket, 'Key' => $key, 'Content' => $content, )); }else{ $client->putObject( array( 'Bucket' => $bucket, 'Key' => $key, 'Content' => fopen($content, 'r'), 'ContentLength' => filesize($content), )); } } //下载文件 function download(OSSClient $client, $bucket, $key){ $object = $client->getObject( array( 'Bucket' => $bucket, 'Key' => $key, )); echo (string)$object; } // 删除bucket function deleteBucket(OSSClient $client, $bucket) { $client->deleteBucket( array( 'Bucket' => $bucket, )); } $keyId = '5WTGMhX6mQX6Q***'; $keySecret = 'VDISRNuHEY0THb9v1RYv08vj4lc***'; $client = createClient($keyId, $keySecret); $bucket = 'xiaoqiangbucket'; $key = rand(1,1000); $content = "this is xiaoqiang's content"; //$content = array(1,2,3,4,5,6,7,8); listBuckets($client); //显示所有bucket createBucket($client, $bucket); //新建一个bucket getBucketAcl($client, $bucket); download($client, $bucket, $key); //下载key为$key的content upload($client, $bucket, $key, $content,0); //上传$key=>$content到bucket var_dump(getBucketKey($client, $bucket));//显示bucket内的所有key //deleteBucket($client, $bucket); //删除bucket
至此在客户端实现了控制台的所有操。