要操作Amazon的S3除了進官方的Web介面及SDK操作外,也有其他人開發了PHP版本的API讓開發者可以直接從程式端操作

amazon-s3-php-class API doc
amazon-s3-php-class source

範例:

//Require S3 Class	
require_once 'S3.php';

// AWS access info
define('awsAccessKey', 'awsAccessKey');
define('awsSecretKey', 'awsSecretKey');


// Check for CURL
if (!extension_loaded('curl') && !@dl(PHP_SHLIB_SUFFIX == 'so' ? 'curl.so' : 'php_curl.dll')) {
	exit("ERROR: CURL extension not loaded");
}

$s3 = new S3(awsAccessKey, awsSecretKey);
//機器的Endpoint(看當初機器開在哪邊)
$s3->setEndpoint('s3-us-west-1.amazonaws.com');

//顯示S3 Bucket清單
print_r( $s3->listBuckets() );

//建立Bucket
$s3->putBucket("Bucket_name", S3::ACL_PUBLIC_READ);

//上傳檔案
$s3->putObjectFile("UploadFile", "Bucket_name", "FileName", S3::ACL_PUBLIC_READ);

//Bucket 檔案清單
print_r( $s3->getBucket("Bucket_name") );

//查詢Bucket上的檔案資訊
print_r( $s3->getObjectInfo("Bucket_name", "FileName") );

//刪除檔案
$s3->deleteObject("Bucket_name", "FileName");

//刪除Bucket
$s3->deleteBucket("Bucket_name");

//取得檔案存取權限
print_r( $s3->getAccessControlPolicy("Bucket_name", "FileName") );

//修改檔案存取權限(將檔案設定成可以所有人下載)
$acp = $s3->getAccessControlPolicy("Bucket_name", "FileName");
$acp["acl"][] = array(
		"type" => "Group",
		"uri" => "http://acs.amazonaws.com/groups/global/AllUsers",
		"permission" => "READ"
	);
$s3->setAccessControlPolicy("Bucket_name", "FileName", $acp);
Categories: PHP