開放存儲服務(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 至此在客戶端實現了控制台的所有操。