first commit

This commit is contained in:
Your Name
2026-01-19 14:19:22 +08:00
commit fe2d9c1868
4777 changed files with 665503 additions and 0 deletions

View File

@@ -0,0 +1,254 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
$bucket = Common::getBucketName();
//******************************* Simple Usage****************************************************************
// Create a bucket
$ossClient->createBucket($bucket, OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE);
Common::println("bucket $bucket created");
// Check whether a bucket exists
$doesExist = $ossClient->doesBucketExist($bucket);
Common::println("bucket $bucket exist? " . ($doesExist ? "yes" : "no"));
// Get the region of bucket
$regions = $ossClient->getBucketLocation($bucket);
Common::println("bucket $bucket region: " .print_r($regions,true));
// Get the meta of a bucket
$metas = $ossClient->getBucketMeta($bucket);
Common::println("bucket $bucket meta: " .print_r($metas,true));
// Get the info of bucket
$info = $ossClient->getBucketInfo($bucket);
Common::println("bucket name:".$info->getName()."\n");
Common::println("bucket location:". $info->getLocation()."\n");
Common::println("bucket creation time:".$info->getCreateDate()."\n");
Common::println("bucket storage class:".$info->getStorageClass()."\n");
Common::println("bucket extranet endpoint:".$info->getExtranetEndpoint()."\n");
Common::println("bucket intranet endpoint:".$info->getIntranetEndpoint()."\n");
// Get the bucket list
$bucketListInfo = $ossClient->listBuckets();
// Set bucket ACL
$ossClient->putBucketAcl($bucket, OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE);
Common::println("bucket $bucket acl put");
// Get bucket ACL
$acl = $ossClient->getBucketAcl($bucket);
Common::println("bucket $bucket acl get: " . $acl);
//******************************* For complete usage, see the following functions ****************************************************
createBucket($ossClient, $bucket);
doesBucketExist($ossClient, $bucket);
getBucketLocation($ossClient, $bucket);
getBucketMeta($ossClient,$bucket);
getBucketInfo($ossClient, $bucket);
deleteBucket($ossClient, $bucket);
putBucketAcl($ossClient, $bucket);
getBucketAcl($ossClient, $bucket);
listBuckets($ossClient);
/**
* Create a new bucket
* acl indicates the access permission of a bucket, including: private, public-read-only/private-read-write, and public read-write.
* Private indicates that only the bucket owner or authorized users can access the data..
* The three permissions are separately defined by (OssClient::OSS_ACL_TYPE_PRIVATE,OssClient::OSS_ACL_TYPE_PUBLIC_READ, OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE)
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function createBucket($ossClient, $bucket)
{
try {
$ossClient->createBucket($bucket, OssClient::OSS_ACL_TYPE_PUBLIC_READ_WRITE);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Check whether a bucket exists.
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
*/
function doesBucketExist($ossClient, $bucket)
{
try {
$res = $ossClient->doesBucketExist($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
if ($res === true) {
print(__FUNCTION__ . ": OK" . "\n");
} else {
print(__FUNCTION__ . ": FAILED" . "\n");
}
}
/**
* Get the info of bucket
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
*/
function getBucketInfo($ossClient, $bucket)
{
try {
$info = $ossClient->getBucketInfo($bucket);
printf("bucket name:%s\n", $info->getName());
printf("bucket location:%s\n", $info->getLocation());
printf("bucket creation time:%s\n", $info->getCreateDate());
printf("bucket storage class:%s\n", $info->getStorageClass());
printf("bucket extranet endpoint:%s\n", $info->getExtranetEndpoint());
printf("bucket intranet endpoint:%s\n", $info->getIntranetEndpoint());
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Get the meta of a bucket
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
*/
function getBucketLocation($ossClient, $bucket)
{
try {
$regions = $ossClient->getBucketLocation($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print("bucket $bucket region: " .print_r($regions,true));
}
/**
* Get the bucket's meta
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
*/
function getBucketMeta($ossClient, $bucket)
{
try {
$metas = $ossClient->getBucketMeta($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
print("bucket $bucket meta: " .print_r($metas,true));
}
/**
* Delete a bucket. If the bucket is not empty, the deletion fails.
* A bucket which is not empty indicates that it does not contain any objects or parts that are not completely uploaded during multipart upload
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to delete
* @return null
*/
function deleteBucket($ossClient, $bucket)
{
try {
$ossClient->deleteBucket($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Set bucket ACL
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function putBucketAcl($ossClient, $bucket)
{
$acl = OssClient::OSS_ACL_TYPE_PRIVATE;
try {
$ossClient->putBucketAcl($bucket, $acl);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Get bucket ACL
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function getBucketAcl($ossClient, $bucket)
{
try {
$res = $ossClient->getBucketAcl($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
print('acl: ' . $res);
}
/**
* List all buckets
*
* @param OssClient $ossClient OssClient instance
* @return null
*/
function listBuckets($ossClient)
{
$bucketList = null;
try {
$bucketListInfo = $ossClient->listBuckets();
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
$bucketList = $bucketListInfo->getBucketList();
foreach ($bucketList as $bucket) {
print($bucket->getLocation() . "\t" . $bucket->getName() . "\t" . $bucket->getCreatedate() . "\n");
}
}

View File

@@ -0,0 +1,91 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//*******************************Simple Usage ***************************************************************
// Add Canme record
$myDomain = '<yourDomainName>';
$ossClient->addBucketCname($bucket, $myDomain);
// View cname records
$cnameConfig = $ossClient->getBucketCname($bucket);
Common::println("bucket $bucket cname:" . $cnameConfig->serializeToXml());
// Delete bucket cname
$myDomain = '<yourDomainName>';
$ossClient->deleteBucketCname($bucket,$myDomain);
Common::println("bucket $bucket cname deleted");
//******************************* For complete usage, see the following functions ****************************************************
addBucketCname($ossClient, $bucket);
getBucketCname($ossClient, $bucket);
deleteBucketCname($ossClient, $bucket);
/**
* Set bucket cname
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function addBucketCname($ossClient, $bucket)
{
// Set up a custom domain name.
$myDomain = '<yourDomainName>';
try {
$ossClient->addBucketCname($bucket, $myDomain);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Get bucket cname
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function getBucketCname($ossClient, $bucket)
{
try {
$cnameConfig = $ossClient->getBucketCname($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
print($cnameConfig->serializeToXml() . "\n");
}
/**
* Delete bucket cname
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function deleteBucketCname($ossClient, $bucket)
{
$myDomain = '<yourDomainName>';
try {
$ossClient->deleteBucketCname($bucket, $myDomain);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@@ -0,0 +1,108 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Model\CorsConfig;
use OSS\Model\CorsRule;
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
$bucket = Common::getBucketName();
//******************************* Simple usage****************************************************************
// Set cors configuration
$corsConfig = new CorsConfig();
$rule = new CorsRule();
$rule->addAllowedHeader("x-oss-header");
$rule->addAllowedOrigin("http://www.b.com");
$rule->addAllowedMethod("POST");
$rule->setMaxAgeSeconds(10);
$corsConfig->addRule($rule);
$ossClient->putBucketCors($bucket, $corsConfig);
Common::println("bucket $bucket corsConfig created:" . $corsConfig->serializeToXml());
// Get cors configuration
$corsConfig = $ossClient->getBucketCors($bucket);
Common::println("bucket $bucket corsConfig fetched:" . $corsConfig->serializeToXml());
// Delete cors configuration
$ossClient->deleteBucketCors($bucket);
Common::println("bucket $bucket corsConfig deleted");
//******************************* For complete usage, see the following functions *****************************************************
putBucketCors($ossClient, $bucket);
getBucketCors($ossClient, $bucket);
deleteBucketCors($ossClient, $bucket);
getBucketCors($ossClient, $bucket);
/**
* Set bucket cores
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function putBucketCors($ossClient, $bucket)
{
$corsConfig = new CorsConfig();
$rule = new CorsRule();
$rule->addAllowedHeader("x-oss-header");
$rule->addAllowedOrigin("http://www.b.com");
$rule->addAllowedMethod("POST");
$rule->setMaxAgeSeconds(10);
$corsConfig->addRule($rule);
try {
$ossClient->putBucketCors($bucket, $corsConfig);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Get and print the cors configuration of a bucket
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function getBucketCors($ossClient, $bucket)
{
$corsConfig = null;
try {
$corsConfig = $ossClient->getBucketCors($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
print($corsConfig->serializeToXml() . "\n");
}
/**
* Delete all cors configuraiton of a bucket
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function deleteBucketCors($ossClient, $bucket)
{
try {
$ossClient->deleteBucketCors($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@@ -0,0 +1,98 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Model\ServerSideEncryptionConfig;
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
$bucket = Common::getBucketName();
//******************************* Simple Usage****************************************************************
// Configure Bucket encryption
// Set Bucket's default server-side encryption method to OSS fully managed encryption (SSE-OSS).
$config = new ServerSideEncryptionConfig("AES256");
// Set Bucket's default server-side encryption method to KMS, and do not specify a CMK ID.
//$config = new ServerSideEncryptionConfig("KMS");
// Set Bucket's default server-side encryption method to KMS, and specify the CMK ID.
//$config = new ServerSideEncryptionConfig("KMS", "your kms id");
$ossClient->putBucketEncryption($bucket, $config);
Common::println("bucket $bucket encryoption created");
$config = $ossClient->getBucketEncryption($bucket);
Common::println("bucket $bucket encryoption:".$config->serializeToXml());
$config = $ossClient->deleteBucketEncryption($bucket);
Common::println("bucket $bucket encryoption has deleted");
//******************************* For complete usage, see the following functions ****************************************************
putBucketEncryption($ossClient, $bucket);
getBucketEncryption($ossClient, $bucket);
deleteBucketEncryption($ossClient, $bucket);
/**
* Configure Bucket encryption
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function putBucketEncryption($ossClient,$bucket){
try {
// Set Bucket's default server-side encryption method to OSS fully managed encryption (SSE-OSS).
$config = new ServerSideEncryptionConfig("AES256");
// Set Bucket's default server-side encryption method to KMS, and do not specify a CMK ID.
//$config = new ServerSideEncryptionConfig("KMS");
// Set Bucket's default server-side encryption method to KMS, and specify the CMK ID.
//$config = new ServerSideEncryptionConfig("KMS", "your kms id");
$ossClient->putBucketEncryption($bucket, $config);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Get Bucket encryption
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function getBucketEncryption($ossClient,$bucket){
try {
$config = $ossClient->getBucketEncryption($bucket);
print($config->getSSEAlgorithm());
print($config->getKMSMasterKeyID());
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Delete Bucket encryption
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function deleteBucketEncryption($ossClient,$bucket){
try {
$ossClient->deleteBucketEncryption($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@@ -0,0 +1,109 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Model\LifecycleAction;
use OSS\Model\LifecycleConfig;
use OSS\Model\LifecycleRule;
$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//******************************* Simple Usage *******************************************************
// Set lifecycle configuration
$lifecycleConfig = new LifecycleConfig();
$actions = array();
$actions[] = new LifecycleAction("Expiration", "Days", 3);
$lifecycleRule = new LifecycleRule("delete obsoleted files", "obsoleted/", "Enabled", $actions);
$lifecycleConfig->addRule($lifecycleRule);
$ossClient->putBucketLifecycle($bucket, $lifecycleConfig);
Common::println("bucket $bucket lifecycleConfig created:" . $lifecycleConfig->serializeToXml());
// Get lifecycle configuration
$lifecycleConfig = $ossClient->getBucketLifecycle($bucket);
Common::println("bucket $bucket lifecycleConfig fetched:" . $lifecycleConfig->serializeToXml());
// Delete bucket lifecycle configuration
$ossClient->deleteBucketLifecycle($bucket);
Common::println("bucket $bucket lifecycleConfig deleted");
//***************************** For complete usage, see the following functions ***********************************************
putBucketLifecycle($ossClient, $bucket);
getBucketLifecycle($ossClient, $bucket);
deleteBucketLifecycle($ossClient, $bucket);
getBucketLifecycle($ossClient, $bucket);
/**
* Set bucket lifecycle configuration
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function putBucketLifecycle($ossClient, $bucket)
{
$lifecycleConfig = new LifecycleConfig();
$actions = array();
$actions[] = new LifecycleAction(OssClient::OSS_LIFECYCLE_EXPIRATION, OssClient::OSS_LIFECYCLE_TIMING_DAYS, 3);
$lifecycleRule = new LifecycleRule("delete obsoleted files", "obsoleted/", "Enabled", $actions);
$lifecycleConfig->addRule($lifecycleRule);
$actions = array();
$actions[] = new LifecycleAction(OssClient::OSS_LIFECYCLE_EXPIRATION, OssClient::OSS_LIFECYCLE_TIMING_DATE, '2022-10-12T00:00:00.000Z');
$lifecycleRule = new LifecycleRule("delete temporary files", "temporary/", "Enabled", $actions);
$lifecycleConfig->addRule($lifecycleRule);
try {
$ossClient->putBucketLifecycle($bucket, $lifecycleConfig);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Get bucket lifecycle configuration
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function getBucketLifecycle($ossClient, $bucket)
{
$lifecycleConfig = null;
try {
$lifecycleConfig = $ossClient->getBucketLifecycle($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
print($lifecycleConfig->serializeToXml() . "\n");
}
/**
* Delete bucket lifecycle configuration
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function deleteBucketLifecycle($ossClient, $bucket)
{
try {
$ossClient->deleteBucketLifecycle($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@@ -0,0 +1,95 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//*******************************Simple Usage ***************************************************************
// Set bucket access logging rules. Access logs are stored under the same bucket with a 'access.log' prefix.
$ossClient->putBucketLogging($bucket, $bucket, "access.log", array());
Common::println("bucket $bucket lifecycleConfig created");
// Get bucket access logging rules
$loggingConfig = $ossClient->getBucketLogging($bucket, array());
Common::println("bucket $bucket lifecycleConfig fetched:" . $loggingConfig->serializeToXml());
// Delete bucket access logging rules
$loggingConfig = $ossClient->getBucketLogging($bucket, array());
Common::println("bucket $bucket lifecycleConfig deleted");
//******************************* For complete usage, see the following functions ****************************************************
putBucketLogging($ossClient, $bucket);
getBucketLogging($ossClient, $bucket);
deleteBucketLogging($ossClient, $bucket);
getBucketLogging($ossClient, $bucket);
/**
* Set bucket logging configuration
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function putBucketLogging($ossClient, $bucket)
{
$option = array();
// Access logs are stored in the same bucket.
$targetBucket = $bucket;
$targetPrefix = "access.log";
try {
$ossClient->putBucketLogging($bucket, $targetBucket, $targetPrefix, $option);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Get bucket logging configuration
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function getBucketLogging($ossClient, $bucket)
{
$loggingConfig = null;
$options = array();
try {
$loggingConfig = $ossClient->getBucketLogging($bucket, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
print($loggingConfig->serializeToXml() . "\n");
}
/**
* Delete bucket logging configuration
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function deleteBucketLogging($ossClient, $bucket)
{
try {
$ossClient->deleteBucketLogging($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@@ -0,0 +1,116 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
$bucket = Common::getBucketName();
//******************************* Simple Usage****************************************************************
//Set requester payment mode
$ossClient->putBucketRequestPayment($bucket, "Requester");
//Get requester payment mode configuration
$payer = $ossClient->getBucketRequestPayment($bucket);
Common::println("bucket $bucket Payer:".$payer.PHP_EOL);
//Third-party paid access to Object
$options = array(
OssClient::OSS_HEADERS => array(
OssClient::OSS_REQUEST_PAYER => 'requester',
));
$content = "hello";
$object = "object";
//PutObject interface to specify the payer
$ossClient->putObject($bucket, $object, $content, $options);
// GetObject interface to specify the payer
$ossClient->getObject($bucket, $object, $options);
// DeleteObject interface to specify the payer
$ossClient->deleteObject($bucket, $object, $options);
//******************************* For complete usage, see the following functions ****************************************************
putBucketRequestPayment($ossClient,$bucket);
getBucketRequestPayment($ossClient,$bucket);
setObjectPayment($ossClient,$bucket);
/**
* Set requester payment mode
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function putBucketRequestPayment($ossClient, $bucket)
{
try {
$ossClient->putBucketRequestPayment($bucket, "Requester");
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Get payment mode of bucket
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function getBucketRequestPayment($ossClient, $bucket)
{
try {
$payer = $ossClient->getBucketRequestPayment($bucket);
print("bucket $bucket Payer:".$payer.PHP_EOL);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Set payment mode of object
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function setObjectPayment($ossClient,$bucket){
// Specify the payment model for the requester.
$options = array(
OssClient::OSS_HEADERS => array(
OssClient::OSS_REQUEST_PAYER => 'requester',
));
try {
$content = "hello";
$object = "object";
//PutObject interface to specify the payer
$ossClient->putObject($bucket, $object, $content, $options);
// GetObject interface to specify the payer
$ossClient->getObject($bucket, $object, $options);
// DeleteObject interface to specify the payer
$ossClient->deleteObject($bucket, $object, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@@ -0,0 +1,123 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
$bucket = Common::getBucketName();
//******************************* Simple Usage****************************************************************
// Set Bucket Policy
// Authorization strategy.
$policy = <<< BBBB
{
"Version":"1",
"Statement":[
{
"Action":[
"oss:PutObject",
"oss:GetObject"
],
"Effect":"Allow",
"Resource":["acs:oss:*:*:*/user1/*"]
}
]
}
BBBB;
$ossClient->putBucketPolicy($bucket, $policy);
// Get bucket pllicy
$policy = $ossClient->getBucketPolicy($bucket);
Common::println("bucket $bucket policy: " . $policy);
// Delete bucket pllicy
$policy = $ossClient->deleteBucketPolicy($bucket);
//******************************* For complete usage, see the following functions ****************************************************
putBucketPolicy($ossClient, $bucket);
getBucketPolicy($ossClient, $bucket);
deleteBucketPolicy($ossClient, $bucket);
/**
* Set Bucket Policy
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function putBucketPolicy($ossClient, $bucket)
{
$policy = <<< BBBB
{
"Version":"1",
"Statement":[
{
"Action":[
"oss:PutObject",
"oss:GetObject"
],
"Effect":"Allow",
"Resource":["acs:oss:*:*:*/user1/*"]
}
]
}
BBBB;
try {
$ossClient->putBucketPolicy($bucket, $policy);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Get Bucket Policy
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function getBucketPolicy($ossClient, $bucket)
{
try {
$policy = $ossClient->getBucketPolicy($bucket);
print($policy);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Delete Bucket Policy
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function deleteBucketPolicy($ossClient, $bucket)
{
try {
$ossClient->deleteBucketPolicy($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@@ -0,0 +1,101 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
use \OSS\Model\RefererConfig;
$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//******************************* Simple Usage ****************************************************************
// Set referer whitelist
$refererConfig = new RefererConfig();
$refererConfig->setAllowEmptyReferer(true);
$refererConfig->addReferer("www.aliiyun.com");
$refererConfig->addReferer("www.aliiyuncs.com");
$ossClient->putBucketReferer($bucket, $refererConfig);
Common::println("bucket $bucket refererConfig created:" . $refererConfig->serializeToXml());
// Get referer whitelist
$refererConfig = $ossClient->getBucketReferer($bucket);
Common::println("bucket $bucket refererConfig fetched:" . $refererConfig->serializeToXml());
// Delete referrer whitelist
$refererConfig = new RefererConfig();
$ossClient->putBucketReferer($bucket, $refererConfig);
Common::println("bucket $bucket refererConfig deleted");
//******************************* For complete usage, see the following functions ****************************************************
putBucketReferer($ossClient, $bucket);
getBucketReferer($ossClient, $bucket);
deleteBucketReferer($ossClient, $bucket);
getBucketReferer($ossClient, $bucket);
/**
* Set bucket referer configuration
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function putBucketReferer($ossClient, $bucket)
{
$refererConfig = new RefererConfig();
$refererConfig->setAllowEmptyReferer(true);
$refererConfig->addReferer("www.aliiyun.com");
$refererConfig->addReferer("www.aliiyuncs.com");
try {
$ossClient->putBucketReferer($bucket, $refererConfig);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Get bucket referer configuration
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function getBucketReferer($ossClient, $bucket)
{
$refererConfig = null;
try {
$refererConfig = $ossClient->getBucketReferer($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
print($refererConfig->serializeToXml() . "\n");
}
/**
* Delete bucket referer configuration
* Referer whitelist cannot be directly deleted. So use a empty one to overwrite it.
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function deleteBucketReferer($ossClient, $bucket)
{
$refererConfig = new RefererConfig();
try {
$ossClient->putBucketReferer($bucket, $refererConfig);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@@ -0,0 +1,65 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
$bucket = Common::getBucketName();
//******************************* Simple Usage****************************************************************
// Get Bucket Stat
$stat = $ossClient->getBucketStat($bucket);
Common::println("Bucket ".$bucket." current storage is:".$stat->getStorage().PHP_EOL);
Common::println("Bucket ".$bucket." object count is:".$stat->getObjectCount().PHP_EOL);
Common::println("Bucket ".$bucket." multipart upload count is:".$stat->getMultipartUploadCount().PHP_EOL);
Common::println("Bucket ".$bucket." live channel count is:".$stat->getLiveChannelCount().PHP_EOL);
Common::println("Bucket ".$bucket." last modified time is:".$stat->getLastModifiedTime().PHP_EOL);
Common::println("Bucket ".$bucket." standard storage is:".$stat->getStandardStorage().PHP_EOL);
Common::println("Bucket ".$bucket." standard object count is:".$stat->getStandardObjectCount().PHP_EOL);
Common::println("Bucket ".$bucket." infrequent access storage is:".$stat->getInfrequentAccessStorage().PHP_EOL);
Common::println("Bucket ".$bucket." infrequent access real storage is:".$stat->getInfrequentAccessRealStorage().PHP_EOL);
Common::println("Bucket ".$bucket." infrequent access object count is:".$stat->getInfrequentAccessObjectCount().PHP_EOL);
Common::println("Bucket ".$bucket." archive storage is:".$stat->getArchiveStorage().PHP_EOL);
Common::println("Bucket ".$bucket." archive real storage is:".$stat->getArchiveRealStorage().PHP_EOL);
Common::println("Bucket ".$bucket." archive object count is:".$stat->getArchiveObjectCount().PHP_EOL);
Common::println("Bucket ".$bucket." cold archive storage is:".$stat->getColdArchiveStorage().PHP_EOL);
Common::println("Bucket ".$bucket." cold archive real storage is:".$stat->getColdArchiveRealStorage().PHP_EOL);
Common::println("Bucket ".$bucket." cold archive object count is:".$stat->getColdArchiveObjectCount().PHP_EOL);
//******************************* For complete usage, see the following functions ****************************************************
getBucketStat($ossClient,$bucket);
/**
* get bucket stat
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function getBucketStat($ossClient, $bucket)
{
try {
$stat = $ossClient->getBucketStat($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
printf("Bucket ".$bucket." current storage is:".$stat->getStorage().PHP_EOL);
printf("Bucket ".$bucket." object count is:".$stat->getObjectCount().PHP_EOL);
printf("Bucket ".$bucket." multipart upload count is:".$stat->getMultipartUploadCount().PHP_EOL);
printf("Bucket ".$bucket." live channel count is:".$stat->getLiveChannelCount().PHP_EOL);
printf("Bucket ".$bucket." last modified time is:".$stat->getLastModifiedTime().PHP_EOL);
printf("Bucket ".$bucket." standard storage is:".$stat->getStandardStorage().PHP_EOL);
printf("Bucket ".$bucket." standard object count is:".$stat->getStandardObjectCount().PHP_EOL);
printf("Bucket ".$bucket." infrequent access storage is:".$stat->getInfrequentAccessStorage().PHP_EOL);
printf("Bucket ".$bucket." infrequent access real storage is:".$stat->getInfrequentAccessRealStorage().PHP_EOL);
printf("Bucket ".$bucket." infrequent access object count is:".$stat->getInfrequentAccessObjectCount().PHP_EOL);
printf("Bucket ".$bucket." archive storage is:".$stat->getArchiveStorage().PHP_EOL);
printf("Bucket ".$bucket." archive real storage is:".$stat->getArchiveRealStorage().PHP_EOL);
printf("Bucket ".$bucket." archive object count is:".$stat->getArchiveObjectCount().PHP_EOL);
printf("Bucket ".$bucket." cold archive storage is:".$stat->getColdArchiveStorage().PHP_EOL);
printf("Bucket ".$bucket." cold archive real storage is:".$stat->getColdArchiveRealStorage().PHP_EOL);
printf("Bucket ".$bucket." cold archive object count is:".$stat->getColdArchiveObjectCount().PHP_EOL);
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@@ -0,0 +1,112 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Model\TaggingConfig;
use OSS\Model\Tag;
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
$bucket = Common::getBucketName();
//******************************* Simple Usage****************************************************************
// Set bucket tag
$config = new TaggingConfig();
$config->addTag(new Tag("key1", "value1"));
$config->addTag(new Tag("key2", "value2"));
$ossClient->putBucketTags($bucket, $config);
// Get bucket tags
$config = $ossClient->getBucketTags($bucket);
Common::println("bucket $bucket tags: ".$config->serializeToXml());
// Delete bucket tags
// Delete the specified tag of the bucket.
$tags = array();
$tags[] = new Tag("key1", "value1");
$tags[] = new Tag("key2", "value2");
$ossClient->deleteBucketTags($bucket, $tags);
// Delete all tags in the bucket.
$ossClient->deleteBucketTags($bucket);
//******************************* For complete usage, see the following functions ****************************************************
putBucketTags($ossClient, $bucket);
getBucketTags($ossClient, $bucket);
deleteBucketTags($ossClient, $bucket);
/**
* Create bucket tag
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function putBucketTags($ossClient, $bucket)
{
try {
// 设置Bucket标签。
$config = new TaggingConfig();
$config->addTag(new Tag("key1", "value1"));
$config->addTag(new Tag("key2", "value2"));
$ossClient->putBucketTags($bucket, $config);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* get bucket tag
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function getBucketTags($ossClient, $bucket)
{
try {
$config = $ossClient->getBucketTags($bucket);
print_r($config->getTags());
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* delete bucket tag
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function deleteBucketTags($ossClient, $bucket)
{
try {
// Delete the specified tag of the bucket.
$tags = array();
$tags[] = new Tag("key1", "value1");
$tags[] = new Tag("key2", "value2");
$ossClient->deleteBucketTags($bucket, $tags);
// Delete all tags in the bucket.
//$ossClient->deleteBucketTags($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@@ -0,0 +1,61 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
$bucket = Common::getBucketName();
//******************************* Simple Usage****************************************************************
// set <tran></tran>sfer acceleration
$enabled = true; // set true to enable transfer acceleration; set false to disalbe transfer acceleration
$ossClient->putBucketTransferAcceleration($bucket, $enabled);
printf('putBucketTransferAcceleration SUCCESS' . "\n");
// get transfer acceleration
$result = $ossClient->getBucketTransferAcceleration($bucket);
printf('getBucketTransferAcceleration Status:%s'."\n",$result);
//******************************* For complete usage, see the following functions ****************************************************
putBucketTransferAcceleration($ossClient,$bucket);
getBucketTransferAcceleration($bucket);
/**
* @param $ossClient OssClient
* @param $bucket bucket_name string
* @param $enabled string
*/
function putBucketTransferAcceleration($ossClient, $bucket, $enabled)
{
try{
$enabled = true; // set true to enable transfer acceleration; set false to disalbe transfer acceleration
$ossClient->putBucketTransferAcceleration($bucket,$enabled);
printf('putBucketTransferAcceleration SUCCESS' . "\n");
} catch(OssException $e) {
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* @param $ossClient OssClient
* @param $bucket bucket_name string
*/
function getBucketTransferAcceleration($ossClient, $bucket)
{
try{
$result = $ossClient->getBucketTransferAcceleration($bucket);
printf('getBucketTransferAcceleration Status:%s'."\n",$result);
} catch(OssException $e) {
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@@ -0,0 +1,235 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
$bucket = Common::getBucketName();
//******************************* Simple Usage****************************************************************
//Set Bucket version control status
//Set the storage space version control to enable version control (Enabled) or suspend version control (Suspended).
$ossClient->putBucketVersioning($bucket, "Enabled");
Common::println("bucket $bucket version Enabled");
// show all object list
$option = array(
OssClient::OSS_KEY_MARKER => null,
OssClient::OSS_VERSION_ID_MARKER => null
);
$bool = true;
while ($bool) {
$result = $ossClient->listObjectVersions($bucket, $option);
## View the version information of the listed object.
foreach ($result->getObjectVersionList() as $key => $info) {
Common::println("key name: " . $info->getKey());
Common::println("versionid: " . $info->getVersionId());
Common::println("Is latest: " . $info->getIsLatest());
}
## View the version information that lists the deletion flags.
foreach ($result->getDeleteMarkerList() as $key => $info) {
Common::println("del_maker key name: " . $info->getKey());
Common::println("del_maker versionid: " . $info->getVersionId());
Common::println("del_maker Is latest: " . $info->getIsLatest());
}
if ($result->getIsTruncated() === 'true') {
$option = array(
OssClient::OSS_KEY_MARKER => $result->getNextKeyMarker(),
OssClient::OSS_VERSION_ID_MARKER => $result->getNextVersionIdMarker()
);
} else {
$bool = false;
}
}
// show the prefix object
$option = array(
OssClient::OSS_KEY_MARKER => null,
OssClient::OSS_VERSION_ID_MARKER => null,
OssClient::OSS_PREFIX => "test"
);
$bool = true;
while ($bool) {
$result = $ossClient->listObjectVersions($bucket, $option);
## View the version information of the listed object.
foreach ($result->getObjectVersionList() as $key => $info) {
Common::println("key name: " . $info->getKey());
Common::println("versionid: " . $info->getVersionId());
Common::println("Is latest: " . $info->getIsLatest());
}
## View the version information that lists the deletion flags.
foreach ($result->getDeleteMarkerList() as $key => $info) {
Common::println("del_maker key name: " . $info->getKey());
Common::println("del_maker versionid: " . $info->getVersionId());
Common::println("del_maker Is latest: " . $info->getIsLatest());
}
if ($result->getIsTruncated() === 'true') {
$option[OssClient::OSS_KEY_MARKER] = $result->getNextKeyMarker();
$option[OssClient::OSS_VERSION_ID_MARKER] = $result->getNextVersionIdMarker();
} else {
$bool = false;
}
}
// list the number of objects
$option = array(
OssClient::OSS_KEY_MARKER => null,
OssClient::OSS_VERSION_ID_MARKER => null,
OssClient::OSS_MAX_KEYS => 200
);
$result = $ossClient->listObjectVersions($bucket, $option);
## View the version information of the listed object.
foreach ($result->getObjectVersionList() as $key => $info) {
Common::println("key name: " . $info->getKey());
Common::println("versionid: " . $info->getVersionId());
Common::println("Is latest: " . $info->getIsLatest());
}
## View the version information that lists the deletion flags.
foreach ($result->getDeleteMarkerList() as $key => $info) {
Common::println("del_maker key name: " . $info->getKey());
Common::println("del_maker versionid: " . $info->getVersionId());
Common::println("del_maker Is latest: " . $info->getIsLatest());
}
// show root folder list
$option = array(
OssClient::OSS_KEY_MARKER => null,
OssClient::OSS_VERSION_ID_MARKER => null,
OssClient::OSS_DELIMITER => "/",
);
$bool = true;
while ($bool) {
$result = $ossClient->listObjectVersions($bucket, $option);
## View the version information of the listed object.
foreach ($result->getObjectVersionList() as $key => $info) {
Common::println("key name: " . $info->getKey());
Common::println("versionid: " . $info->getVersionId());
Common::println("Is latest: " . $info->getIsLatest());
}
## View the version information that lists the deletion flags.
foreach ($result->getDeleteMarkerList() as $key => $info) {
Common::println("del_maker key name: " . $info->getKey());
Common::println("del_maker versionid: " . $info->getVersionId());
Common::println("del_maker Is latest: " . $info->getIsLatest());
}
if ($result->getIsTruncated() === 'true') {
$option[OssClient::OSS_KEY_MARKER] = $result->getNextKeyMarker();
$option[OssClient::OSS_VERSION_ID_MARKER] = $result->getNextVersionIdMarker();
} else {
$bool = false;
}
}
// Show subfolder objects list
$option = array(
OssClient::OSS_KEY_MARKER => null,
OssClient::OSS_VERSION_ID_MARKER => null,
OssClient::OSS_DELIMITER => "/",
OssClient::OSS_PREFIX => "test/",
);
$bool = true;
while ($bool) {
$result = $ossClient->listObjectVersions($bucket, $option);
## View the version information of the listed object.
foreach ($result->getObjectVersionList() as $key => $info) {
Common::println("key name: " . $info->getKey());
Common::println("versionid: " . $info->getVersionId());
Common::println("Is latest: " . $info->getIsLatest());
}
## View the version information that lists the deletion flags.
foreach ($result->getDeleteMarkerList() as $key => $info) {
Common::println("del_maker key name: " . $info->getKey());
Common::println("del_maker versionid: " . $info->getVersionId());
Common::println("del_maker Is latest: " . $info->getIsLatest());
}
if ($result->getIsTruncated() === 'true') {
$option[OssClient::OSS_KEY_MARKER] = $result->getNextKeyMarker();
$option[OssClient::OSS_VERSION_ID_MARKER] = $result->getNextVersionIdMarker();
} else {
$bool = false;
}
}
//******************************* For complete usage, see the following functions ****************************************************
listObjectVersions($ossClient, $bucket);
putBucketVersioning($ossClient, $bucket);
/**
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function listObjectVersions($ossClient, $bucket)
{
try {
$option = array(
OssClient::OSS_KEY_MARKER => null,
OssClient::OSS_VERSION_ID_MARKER => null,
);
$bool = true;
while ($bool) {
$result = $ossClient->listObjectVersions($bucket, $option);
## View the version information of the listed object.
foreach ($result->getObjectVersionList() as $key => $info) {
Common::println("key name: " . $info->getKey());
Common::println("versionid: " . $info->getVersionId());
Common::println("Is latest: " . $info->getIsLatest());
}
## View the version information that lists the deletion flags.
foreach ($result->getDeleteMarkerList() as $key => $info) {
Common::println("del_maker key name: " . $info->getKey());
Common::println("del_maker versionid: " . $info->getVersionId());
Common::println("del_maker Is latest: " . $info->getIsLatest());
}
if ($result->getIsTruncated() === 'true') {
$option[OssClient::OSS_KEY_MARKER] = $result->getNextKeyMarker();
$option[OssClient::OSS_VERSION_ID_MARKER] = $result->getNextVersionIdMarker();
} else {
$bool = false;
}
}
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Enabled or Suspended bucket version
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function putBucketVersioning($ossClient, $bucket)
{
try {
//Set the storage space version control to enable version control (Enabled) or suspend version control (Suspended).
$ossClient->putBucketVersioning($bucket, "Enabled");
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@@ -0,0 +1,92 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Model\WebsiteConfig;
$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//******************************* Simple Usage ***************************************************************
// Set bucket static website configuration
$websiteConfig = new WebsiteConfig("index.html", "error.html");
$ossClient->putBucketWebsite($bucket, $websiteConfig);
Common::println("bucket $bucket websiteConfig created:" . $websiteConfig->serializeToXml());
// Get bucket static website configuration
$websiteConfig = $ossClient->getBucketWebsite($bucket);
Common::println("bucket $bucket websiteConfig fetched:" . $websiteConfig->serializeToXml());
// Delete bucket static website configuration
$ossClient->deleteBucketWebsite($bucket);
Common::println("bucket $bucket websiteConfig deleted");
//******************************* For complete usage, see the following functions ****************************************************
putBucketWebsite($ossClient, $bucket);
getBucketWebsite($ossClient, $bucket);
deleteBucketWebsite($ossClient, $bucket);
getBucketWebsite($ossClient, $bucket);
/**
* Sets bucket static website configuration
*
* @param $ossClient OssClient
* @param $bucket string bucket name
* @return null
*/
function putBucketWebsite($ossClient, $bucket)
{
$websiteConfig = new WebsiteConfig("index.html", "error.html");
try {
$ossClient->putBucketWebsite($bucket, $websiteConfig);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Get bucket static website configuration
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function getBucketWebsite($ossClient, $bucket)
{
$websiteConfig = null;
try {
$websiteConfig = $ossClient->getBucketWebsite($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
print($websiteConfig->serializeToXml() . "\n");
}
/**
* Delete bucket static website configuration
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function deleteBucketWebsite($ossClient, $bucket)
{
try {
$ossClient->deleteBucketWebsite($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@@ -0,0 +1,145 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
$bucket = Common::getBucketName();
//******************************* Simple Usage****************************************************************
// Create a new compliance retention policy:
// The specified object protection days are 30 days.
$wormId = $ossClient->initiateBucketWorm($bucket, 30);
Common::println("bucket $bucket wormId: " . $wormId.PHP_EOL);
// Cancel an unlocked compliance retention policy
$ossClient->abortBucketWorm($bucket);
//Lock compliant retention policy
$wormId = $ossClient->initiateBucketWorm($bucket, 30);
$ossClient->completeBucketWorm($bucket, $wormId);
// Get compliant retention policy
$config = $ossClient->getBucketWorm($bucket);
Common::println("WormId:".$config->getWormId().PHP_EOL);
Common::println("State:". $config->getState().PHP_EOL);
Common::println("Day:". $config->getDay().PHP_EOL);
// Extend the retention days of objects
$wormId = "<yourWormId>";
// Extend the retention days of objects in the locked compliance retention policy to 120 days.
$ossClient->extendBucketWorm($bucket, $wormId, 120);
//******************************* For complete usage, see the following functions ****************************************************
initiateBucketWorm($ossClient, $bucket);
abortBucketWorm($ossClient, $bucket);
completeBucketWorm($ossClient, $bucket);
getBucketWorm($ossClient, $bucket);
extendBucketWorm($ossClient, $bucket);
/**
* Set Bucket Worm Ploicy
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function initiateBucketWorm($ossClient, $bucket)
{
try {
$wormId = $ossClient->initiateBucketWorm($bucket,30);
print("bucket $bucket wormId: " . $wormId.PHP_EOL);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Cancel an unlocked compliance retention policy
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket Name of the bucket to create
* @return null
*/
function abortBucketWorm($ossClient, $bucket)
{
try {
$ossClient->abortBucketWorm($bucket);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Complete Bucket Worm
* @param $ossClient $ossClient OssClient instance
* @param $bucket $bucket Name of the bucket to create
*/
function completeBucketWorm($ossClient, $bucket)
{
try {
$wormId = $ossClient->initiateBucketWorm($bucket, 30);
$ossClient->completeBucketWorm($bucket, $wormId);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Get Bucket Worm
* @param $ossClient $ossClient OssClient instance
* @param $bucket $bucket Name of the bucket to create
*/
function getBucketWorm($ossClient, $bucket)
{
try {
$config = $ossClient->getBucketWorm($bucket);
printf("WormId:%s\n", $config->getWormId());
printf("State:%s\n", $config->getState());
printf("Day:%d\n", $config->getDay());
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Extend the retention days of objects
* @param $ossClient $ossClient OssClient instance
* @param $bucket $bucket Name of the bucket to create
*/
function extendBucketWorm($ossClient, $bucket)
{
$wormId = "<yourWormId>";
try {
$ossClient->ExtendBucketWorm($bucket, $wormId, 120);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@@ -0,0 +1,83 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//******************************* Simple Usage ***************************************************************
/** putObject Upload content to an OSS file using callback.
* The callbackurl specifies the server url for the request callback.
* The callbackbodytype can be application/json or application/x-www-form-urlencoded,the optional parameters,the default for the application/x - WWW - form - urlencoded
* Users can choose not to set OSS_BACK_VAR
*/
$url =
'{
"callbackUrl":"callback.oss-demo.com:23450",
"callbackHost":"oss-cn-hangzhou.aliyuncs.com",
"callbackBody":"bucket=${bucket}&object=${object}&etag=${etag}&size=${size}&mimeType=${mimeType}&imageInfo.height=${imageInfo.height}&imageInfo.width=${imageInfo.width}&imageInfo.format=${imageInfo.format}&my_var1=${x:var1}&my_var2=${x:var2}",
"callbackBodyType":"application/x-www-form-urlencoded"
}';
$var =
'{
"x:var1":"value1",
"x:var2":"值2"
}';
$options = array(OssClient::OSS_CALLBACK => $url,
OssClient::OSS_CALLBACK_VAR => $var
);
$result = $ossClient->putObject($bucket, "b.file", "random content", $options);
Common::println($result['body']);
Common::println($result['info']['http_code']);
/**
* completeMultipartUpload Upload content to an OSS file using callback.
* callbackurl specifies the server url for the request callback
* The callbackbodytype can be application/json or application/x-www-form-urlencoded,the optional parameters,the default for the application/x - WWW - form - urlencoded
* Users can choose not to set OSS_BACK_VAR.
*/
$object = "multipart-callback-test.txt";
$copiedObject = "multipart-callback-test.txt.copied";
$ossClient->putObject($bucket, $copiedObject, file_get_contents(__FILE__));
/**
* step 1. Initialize a block upload event, that is, a multipart upload process to get an upload id
*/
$upload_id = $ossClient->initiateMultipartUpload($bucket, $object);
/**
* step 2. uploadPartCopy
*/
$copyId = 1;
$eTag = $ossClient->uploadPartCopy($bucket, $copiedObject, $bucket, $object, $copyId, $upload_id);
$upload_parts[] = array(
'PartNumber' => $copyId,
'ETag' => $eTag,
);
$listPartsInfo = $ossClient->listParts($bucket, $object, $upload_id);
/**
* step 3.
*/
$json =
'{
"callbackUrl":"callback.oss-demo.com:23450",
"callbackHost":"oss-cn-hangzhou.aliyuncs.com",
"callbackBody":"{\"mimeType\":${mimeType},\"size\":${size},\"x:var1\":${x:var1},\"x:var2\":${x:var2}}",
"callbackBodyType":"application/json"
}';
$var =
'{
"x:var1":"value1",
"x:var2":"值2"
}';
$options = array(OssClient::OSS_CALLBACK => $json,
OssClient::OSS_CALLBACK_VAR => $var);
$result = $ossClient->completeMultipartUpload($bucket, $object, $upload_id, $upload_parts, $options);
Common::println($result['body']);
Common::println($result['info']['http_code']);

View File

@@ -0,0 +1,84 @@
<?php
if (is_file(__DIR__ . '/../autoload.php')) {
require_once __DIR__ . '/../autoload.php';
}
if (is_file(__DIR__ . '/../vendor/autoload.php')) {
require_once __DIR__ . '/../vendor/autoload.php';
}
require_once __DIR__ . '/Config.php';
use OSS\OssClient;
use OSS\Core\OssException;
/**
* Class Common
*
* The Common class for 【Samples/*.php】 used to obtain OssClient instance and other common functions
*/
class Common
{
const endpoint = Config::OSS_ENDPOINT;
const accessKeyId = Config::OSS_ACCESS_ID;
const accessKeySecret = Config::OSS_ACCESS_KEY;
const bucket = Config::OSS_TEST_BUCKET;
/**
* Get an OSSClient instance according to config.
*
* @return OssClient An OssClient instance
*/
public static function getOssClient()
{
try {
$ossClient = new OssClient(self::accessKeyId, self::accessKeySecret, self::endpoint, false);
} catch (OssException $e) {
printf(__FUNCTION__ . "creating OssClient instance: FAILED\n");
printf($e->getMessage() . "\n");
return null;
}
return $ossClient;
}
public static function getBucketName()
{
return self::bucket;
}
/**
* A tool function which creates a bucket and exists the process if there are exceptions
*/
public static function createBucket()
{
$ossClient = self::getOssClient();
if (is_null($ossClient)) exit(1);
$bucket = self::getBucketName();
$acl = OssClient::OSS_ACL_TYPE_PUBLIC_READ;
try {
$ossClient->createBucket($bucket, $acl);
} catch (OssException $e) {
$message = $e->getMessage();
if (\OSS\Core\OssUtil::startsWith($message, 'http status: 403')) {
echo "Please Check your AccessKeyId and AccessKeySecret" . "\n";
exit(0);
} elseif (strpos($message, "BucketAlreadyExists") !== false) {
echo "Bucket already exists. Please check whether the bucket belongs to you, or it was visited with correct endpoint. " . "\n";
exit(0);
}
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
public static function println($message)
{
if (!empty($message)) {
echo strval($message) . "\n";
}
}
}
# Common::createBucket();

View File

@@ -0,0 +1,15 @@
<?php
/**
* Class Config
*
* Make configurations required by the sample.
* Users can run RunAll.php which runs all the samples after configuring Endpoint, AccessId, and AccessKey.
*/
final class Config
{
const OSS_ACCESS_ID = 'update me';
const OSS_ACCESS_KEY = 'update me';
const OSS_ENDPOINT = 'update me';
const OSS_TEST_BUCKET = 'update me';
}

View File

@@ -0,0 +1,76 @@
<?php
//=============================================================================
//How to use credentials-php to access oss
// step 1:Install credentials-php composer require alibabacloud/credentials
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Credentials\CredentialsProvider;
use AlibabaCloud\Credentials\Credential;
use OSS\Credentials\StaticCredentialsProvider;
// public provider conversion class
class AlibabaCloudCredentialsWrapper implements CredentialsProvider{
/**
* @var Credential
*/
private $warpper;
public function __construct($credential){
$this->warpper = $credential;
}
public function getCredentials(){
$ak = $this->warpper->getAccessKeyId();
$sk = $this->warpper->getAccessKeySecret();
$token = $this->warpper->getSecurityToken();
return new StaticCredentialsProvider($ak, $sk, $token);
}
}
$bucket = Common::getBucketName();
//AccessKey Credentials demo
$credential = new Credential(array(
'type' => 'access_key',
'access_key_id' => '<access_key_id>',
'access_key_secret' => '<accessKey_secret>',
));
$providerWarpper = new AlibabaCloudCredentialsWrapper($credential);
$config = array(
'provider' => $providerWarpper,
'endpoint'=> '<endpoint>'
);
try {
$ossClient = new OssClient($config);
$ossClient->putObject($bucket,'c.file','hi oss,this is credentials test of access key');
$result = $ossClient->getObject($bucket,'c.file');
var_dump($result);
} catch (OssException $e) {
printf($e->getMessage() . "\n");
return;
}
// EcsRamRole Credentials demo
$ecsRamRole = new Credential(array(
'type' => 'ecs_ram_role',
'role_name' => 'EcsRamRoleOssTest',
));
$providerWarpper = new AlibabaCloudCredentialsWrapper($ecsRamRole);
$bucket = 'oss-bucket-cd-yp-test';
$config = array(
'provider' => $providerWarpper,
'endpoint'=> '<endpoint>'
);
try {
$ossClient = new OssClient($config);
$ossClient->putObject($bucket,'c.file','hi oss,this is credentials test of EcsRamRole');
$result = $ossClient->getObject($bucket,'c.file');
var_dump($result);
} catch (OssException $e) {
printf($e->getMessage() . "\n");
return;
}

View File

@@ -0,0 +1,45 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Credentials\StaticCredentialsProvider;
$bucket = Common::getBucketName();
// Access Key Provider demo
$id = '<access_key_id>';
$secret = '<accessKey_secret>';
$provider = new StaticCredentialsProvider($id,$secret);
$config = array(
'provider' => $provider,
'endpoint'=>'<endpoint>'
);
try {
$ossClient = new OssClient($config);
$ossClient->putObject($bucket,'c.file','hi oss,this is credentials test of access key provider');
$result = $ossClient->getObject($bucket,'c.file');
var_dump($result);
} catch (OssException $e) {
printf($e->getMessage() . "\n");
return;
}
// Sts provider demo
$id = '<access_key_id>';
$secret = '<accessKey_secret>';
$token = '<security_token>';
$provider = new StaticCredentialsProvider($id,$secret,$token);
$config = array(
'provider' => $provider,
'endpoint'=> "<endpoint>"
);
try {
$ossClient = new OssClient($config);
$ossClient->putObject($bucket,'c.file','hi oss,this is credentials test of sts provider');
$result = $ossClient->getObject($bucket,'c.file');
var_dump($result);
} catch (OssException $e) {
printf($e->getMessage() . "\n");
return;
}

View File

@@ -0,0 +1,87 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
$bucketName = Common::getBucketName();
$object = "example.jpg";
$ossClient = Common::getOssClient();
$download_file = "download.jpg";
if (is_null($ossClient)) exit(1);
//******************************* Simple Usage ***************************************************************
// Upload example.jpg to the specified bucket and rename it to $object.
$ossClient->uploadFile($bucketName, $object, "example.jpg");
// Image resize
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $download_file,
OssClient::OSS_PROCESS => "image/resize,m_fixed,h_100,w_100", );
$ossClient->getObject($bucketName, $object, $options);
printImage("imageResize",$download_file);
// Image crop
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $download_file,
OssClient::OSS_PROCESS => "image/crop,w_100,h_100,x_100,y_100,r_1", );
$ossClient->getObject($bucketName, $object, $options);
printImage("iamgeCrop", $download_file);
// Image rotate
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $download_file,
OssClient::OSS_PROCESS => "image/rotate,90", );
$ossClient->getObject($bucketName, $object, $options);
printImage("imageRotate", $download_file);
// Image sharpen
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $download_file,
OssClient::OSS_PROCESS => "image/sharpen,100", );
$ossClient->getObject($bucketName, $object, $options);
printImage("imageSharpen", $download_file);
// Add watermark into a image
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $download_file,
OssClient::OSS_PROCESS => "image/watermark,text_SGVsbG8g5Zu-54mH5pyN5YqhIQ", );
$ossClient->getObject($bucketName, $object, $options);
printImage("imageWatermark", $download_file);
// Image format convertion
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $download_file,
OssClient::OSS_PROCESS => "image/format,png", );
$ossClient->getObject($bucketName, $object, $options);
printImage("imageFormat", $download_file);
// Get image information
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $download_file,
OssClient::OSS_PROCESS => "image/info", );
$ossClient->getObject($bucketName, $object, $options);
printImage("imageInfo", $download_file);
/**
* Generate a signed url which could be used in browser to access the object. The expiration time is 1 hour.
*/
$timeout = 3600;
$options = array(
OssClient::OSS_PROCESS => "image/resize,m_lfit,h_100,w_100",
);
$signedUrl = $ossClient->signUrl($bucketName, $object, $timeout, "GET", $options);
Common::println("rtmp url: \n" . $signedUrl);
// Finally delete the $object uploaded.
$ossClient->deleteObject($bucketName, $object);
function printImage($func, $imageFile)
{
$array = getimagesize($imageFile);
Common::println("$func, image width: " . $array[0]);
Common::println("$func, image height: " . $array[1]);
Common::println("$func, image type: " . ($array[2] === 2 ? 'jpg' : 'png'));
Common::println("$func, image size: " . ceil(sprintf('%u',filesize($imageFile))));
}

View File

@@ -0,0 +1,131 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Model\LiveChannelConfig;
$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//******************************* Simple Usage *******************************************************
/**
* Create a Live Channel
* The live channel's name is test_rtmp_live.
* The play url file is named as test.m3u8, which includes 3 ts files.
* The time period of each file is 5 seconds.(It is recommneded value only for demo purpose, the actual period depends on the key frame.)
*
*/
$config = new LiveChannelConfig(array(
'description' => 'live channel test',
'type' => 'HLS',
'fragDuration' => 10,
'fragCount' => 5,
'playListName' => 'hello.m3u8'
));
$info = $ossClient->putBucketLiveChannel($bucket, 'test_rtmp_live', $config);
Common::println("bucket $bucket liveChannel created:\n" .
"live channel name: ". $info->getName() . "\n" .
"live channel description: ". $info->getDescription() . "\n" .
"publishurls: ". $info->getPublishUrls()[0] . "\n" .
"playurls: ". $info->getPlayUrls()[0] . "\n");
/**
* You can use listBucketLiveChannels to list and manage all existing live channels.
* Prefix can be used to filter listed live channels by prefix.
* Max_keys indicates the maximum numbers of live channels that can be listed in an iterator at one time. Its value is 1000 in maximum and 100 by default.
*/
$list = $ossClient->listBucketLiveChannels($bucket);
Common::println("bucket $bucket listLiveChannel:\n" .
"list live channel prefix: ". $list->getPrefix() . "\n" .
"list live channel marker: ". $list->getMarker() . "\n" .
"list live channel maxkey: ". $list->getMaxKeys() . "\n" .
"list live channel IsTruncated: ". $list->getIsTruncated() . "\n" .
"list live channel getNextMarker: ". $list->getNextMarker() . "\n");
foreach($list->getChannelList() as $list)
{
Common::println("bucket $bucket listLiveChannel:\n" .
"list live channel IsTruncated: ". $list->getName() . "\n" .
"list live channel Description: ". $list->getDescription() . "\n" .
"list live channel Status: ". $list->getStatus() . "\n" .
"list live channel getNextMarker: ". $list->getLastModified() . "\n");
}
/**
* Obtain the play_url (url used for rtmp stream pushing.
* If the the bucket is not globally readable and writable,
* the url must be signed as shown in the following.) and pulish_url (the url included in the m3u8 file generated in stream pushing) used to push streams.
*/
$play_url = $ossClient->signRtmpUrl($bucket, "test_rtmp_live", 3600, array('params' => array('playlistName' => 'playlist.m3u8')));
Common::println("bucket $bucket rtmp url: \n" . $play_url);
$play_url = $ossClient->signRtmpUrl($bucket, "test_rtmp_live", 3600);
Common::println("bucket $bucket rtmp url: \n" . $play_url);
/**
* If you want to disable a created live channel (disable the pushing streaming or do not allow stream pushing to an IP address), call putLiveChannelStatus to change the channel status to "Disabled".
* If you want to enable a disabled live channel, call PutLiveChannelStatus to chanage the channel status to "Enabled".
*/
$resp = $ossClient->putLiveChannelStatus($bucket, "test_rtmp_live", "enabled");
/**
* You can callLiveChannelInfo to get the information about a live channel.
*/
$info = $ossClient->getLiveChannelInfo($bucket, 'test_rtmp_live');
Common::println("bucket $bucket LiveChannelInfo:\n" .
"live channel info description: ". $info->getDescription() . "\n" .
"live channel info status: ". $info->getStatus() . "\n" .
"live channel info type: ". $info->getType() . "\n" .
"live channel info fragDuration: ". $info->getFragDuration() . "\n" .
"live channel info fragCount: ". $info->getFragCount() . "\n" .
"live channel info playListName: ". $info->getPlayListName() . "\n");
/**
* Gets the historical pushing streaming records by calling getLiveChannelHistory. Now the max records to return is 10.
*/
$history = $ossClient->getLiveChannelHistory($bucket, "test_rtmp_live");
if (count($history->getLiveRecordList()) != 0)
{
foreach($history->getLiveRecordList() as $recordList)
{
Common::println("bucket $bucket liveChannelHistory:\n" .
"live channel history startTime: ". $recordList->getStartTime() . "\n" .
"live channel history endTime: ". $recordList->getEndTime() . "\n" .
"live channel history remoteAddr: ". $recordList->getRemoteAddr() . "\n");
}
}
/**
* Get the live channel's status by calling getLiveChannelStatus.
* If the live channel is receiving the pushing stream, all attributes in stat_result are valid.
* If the live channel is idle or disabled, then the status is idle or Disabled and other attributes have no meaning.
*/
$status = $ossClient->getLiveChannelStatus($bucket, "test_rtmp_live");
Common::println("bucket $bucket listLiveChannel:\n" .
"live channel status status: ". $status->getStatus() . "\n" .
"live channel status ConnectedTime: ". $status->getConnectedTime() . "\n" .
"live channel status VideoWidth: ". $status->getVideoWidth() . "\n" .
"live channel status VideoHeight: ". $status->getVideoHeight() . "\n" .
"live channel status VideoFrameRate: ". $status->getVideoFrameRate() . "\n" .
"live channel status VideoBandwidth: ". $status->getVideoBandwidth() . "\n" .
"live channel status VideoCodec: ". $status->getVideoCodec() . "\n" .
"live channel status AudioBandwidth: ". $status->getAudioBandwidth() . "\n" .
"live channel status AudioSampleRate: ". $status->getAudioSampleRate() . "\n" .
"live channel status AdioCodec: ". $status->getAudioCodec() . "\n");
/**
* If you want to generate a play url from the ts files generated from pushing streaming, call postVodPlayList.
* Specify the start time to 60 seconds before the current time and the end time to the current time, which means that a video of 60 seconds is generated.
* The playlist file is specified to “vod_playlist.m3u8”, which means that a palylist file named vod_playlist.m3u8 is created after the interface is called.
*/
$current_time = time();
$ossClient->postVodPlaylist($bucket,
"test_rtmp_live", "vod_playlist.m3u8",
array('StartTime' => $current_time - 60,
'EndTime' => $current_time)
);
/**
* Call delete_live_channel to delete a live channel if it will no longer be in used.
*/
$ossClient->deleteBucketLiveChannel($bucket, "test_rtmp_live");

View File

@@ -0,0 +1,182 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssUtil;
use OSS\Core\OssException;
$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//******************************* Simple usage ***************************************************************
/**
* See the putObjectByRawAPis usage in complete example to check out basic multipart upload APIs which can be used as resumable upload.
*/
// Upload a file using the multipart upload interface, which determines to use simple upload or multipart upload based on the file size.
$ossClient->multiuploadFile($bucket, "file.php", __FILE__, array());
Common::println("local file " . __FILE__ . " is uploaded to the bucket $bucket, file.php");
// Upload local directory's data into target dir
$ossClient->uploadDir($bucket, "targetdir", __DIR__);
Common::println("local dir " . __DIR__ . " is uploaded to the bucket $bucket, targetdir/");
// List the incomplete multipart uploads
$listMultipartUploadInfo = $ossClient->listMultipartUploads($bucket, array());
//******************************* For complete usage, see the following functions ****************************************************
multiuploadFile($ossClient, $bucket);
putObjectByRawApis($ossClient, $bucket);
uploadDir($ossClient, $bucket);
listMultipartUploads($ossClient, $bucket);
/**
* Upload files using multipart upload
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function multiuploadFile($ossClient, $bucket)
{
$object = "test/multipart-test.txt";
$file = __FILE__;
$options = array();
try {
$ossClient->multiuploadFile($bucket, $object, $file, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Use basic multipart upload for file upload.
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @throws OssException
*/
function putObjectByRawApis($ossClient, $bucket)
{
$object = "test/multipart-test.txt";
/**
* step 1. Initialize a block upload event, that is, a multipart upload process to get an upload id
*/
try {
$uploadId = $ossClient->initiateMultipartUpload($bucket, $object);
} catch (OssException $e) {
printf(__FUNCTION__ . ": initiateMultipartUpload FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": initiateMultipartUpload OK" . "\n");
/*
* step 2. Upload parts
*/
$partSize = 10 * 1024 * 1024;
$uploadFile = __FILE__;
$uploadFileSize = sprintf('%u',filesize($uploadFile));
$pieces = $ossClient->generateMultiuploadParts($uploadFileSize, $partSize);
$responseUploadPart = array();
$uploadPosition = 0;
$isCheckMd5 = true;
foreach ($pieces as $i => $piece) {
$fromPos = $uploadPosition + (integer)$piece[$ossClient::OSS_SEEK_TO];
$toPos = (integer)$piece[$ossClient::OSS_LENGTH] + $fromPos - 1;
$upOptions = array(
$ossClient::OSS_FILE_UPLOAD => $uploadFile,
$ossClient::OSS_PART_NUM => ($i + 1),
$ossClient::OSS_SEEK_TO => $fromPos,
$ossClient::OSS_LENGTH => $toPos - $fromPos + 1,
$ossClient::OSS_CHECK_MD5 => $isCheckMd5,
);
if ($isCheckMd5) {
$contentMd5 = OssUtil::getMd5SumForFile($uploadFile, $fromPos, $toPos);
$upOptions[$ossClient::OSS_CONTENT_MD5] = $contentMd5;
}
//2. Upload each part to OSS
try {
$responseUploadPart[] = $ossClient->uploadPart($bucket, $object, $uploadId, $upOptions);
} catch (OssException $e) {
printf(__FUNCTION__ . ": initiateMultipartUpload, uploadPart - part#{$i} FAILED\n");
printf($e->getMessage() . "\n");
return;
}
printf(__FUNCTION__ . ": initiateMultipartUpload, uploadPart - part#{$i} OK\n");
}
$uploadParts = array();
foreach ($responseUploadPart as $i => $eTag) {
$uploadParts[] = array(
'PartNumber' => ($i + 1),
'ETag' => $eTag,
);
}
/**
* step 3. Complete the upload
*/
try {
$ossClient->completeMultipartUpload($bucket, $object, $uploadId, $uploadParts);
} catch (OssException $e) {
printf(__FUNCTION__ . ": completeMultipartUpload FAILED\n");
printf($e->getMessage() . "\n");
return;
}
printf(__FUNCTION__ . ": completeMultipartUpload OK\n");
}
/**
* Upload by directories
*
* @param OssClient $ossClient OssClient
* @param string $bucket bucket name
*
*/
function uploadDir($ossClient, $bucket)
{
$localDirectory = ".";
$prefix = "samples/codes";
try {
$ossClient->uploadDir($bucket, $prefix, $localDirectory);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
printf(__FUNCTION__ . ": completeMultipartUpload OK\n");
}
/**
* Get ongoing multipart uploads
*
* @param $ossClient OssClient
* @param $bucket string
*/
function listMultipartUploads($ossClient, $bucket)
{
$options = array(
'max-uploads' => 100,
'key-marker' => '',
'prefix' => '',
'upload-id-marker' => ''
);
try {
$listMultipartUploadInfo = $ossClient->listMultipartUploads($bucket, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": listMultipartUploads FAILED\n");
printf($e->getMessage() . "\n");
return;
}
printf(__FUNCTION__ . ": listMultipartUploads OK\n");
$listUploadInfo = $listMultipartUploadInfo->getUploads();
var_dump($listUploadInfo);
}

View File

@@ -0,0 +1,729 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Model\RestoreConfig;
$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//******************************* Simple usage ***************************************************************
// Upload the in-memory string (hi, oss) to an OSS file
$result = $ossClient->putObject($bucket, "b.file", "hi, oss");
Common::println("b.file is created");
Common::println($result['x-oss-request-id']);
Common::println($result['etag']);
Common::println($result['content-md5']);
Common::println($result['body']);
// Uploads a local file to an OSS file
$result = $ossClient->uploadFile($bucket, "c.file", __FILE__);
Common::println("c.file is created");
Common::println("b.file is created");
Common::println($result['x-oss-request-id']);
Common::println($result['etag']);
Common::println($result['content-md5']);
Common::println($result['body']);
// Download an oss object as an in-memory variable
$content = $ossClient->getObject($bucket, "b.file");
Common::println("b.file is fetched, the content is: " . $content);
// Add a symlink to an object
$content = $ossClient->putSymlink($bucket, "test-symlink", "b.file");
Common::println("test-symlink is created");
Common::println($result['x-oss-request-id']);
Common::println($result['etag']);
// Get a symlink
$content = $ossClient->getSymlink($bucket, "test-symlink");
Common::println("test-symlink refer to : " . $content[OssClient::OSS_SYMLINK_TARGET]);
// Download an object to a local file.
$options = array(
OssClient::OSS_FILE_DOWNLOAD => "./c.file.localcopy",
);
$ossClient->getObject($bucket, "c.file", $options);
Common::println("b.file is fetched to the local file: c.file.localcopy");
Common::println("b.file is created");
// Restore Object
$day = 3;
$tier = 'Expedited';
$config = new RestoreConfig($day,$tier);
$options = array(
OssClient::OSS_RESTORE_CONFIG => $config
);
$ossClient->restoreObject($bucket, 'b.file',$options);
// Copy an object
$result = $ossClient->copyObject($bucket, "c.file", $bucket, "c.file.copy");
Common::println("lastModifiedTime: " . $result[0]);
Common::println("ETag: " . $result[1]);
// Check whether an object exists
$doesExist = $ossClient->doesObjectExist($bucket, "c.file.copy");
Common::println("file c.file.copy exist? " . ($doesExist ? "yes" : "no"));
// Delete an object
$result = $ossClient->deleteObject($bucket, "c.file.copy");
Common::println("c.file.copy is deleted");
Common::println("b.file is created");
Common::println($result['x-oss-request-id']);
// Check whether an object exists
$doesExist = $ossClient->doesObjectExist($bucket, "c.file.copy");
Common::println("file c.file.copy exist? " . ($doesExist ? "yes" : "no"));
// Delete multiple objects in batch
$result = $ossClient->deleteObjects($bucket, array("b.file", "c.file"));
foreach($result as $object)
Common::println($object);
sleep(2);
unlink("c.file.localcopy");
// Normal upload and download speed limit
$object= "b.file";
$content = "hello world";
// The speed limit is 100 KB/s, which is 819200 bit/s.
$options = array(
OssClient::OSS_HEADERS => array(
OssClient::OSS_TRAFFIC_LIMIT => 819200,
));
// Speed limit upload.
$ossClient->putObject($bucket, $object, $content, $options);
// Speed limit download.
$ossClient->getObject($bucket, $object, $options);
// Signed URL upload and download speed limit
// Create a URL for uploading with a limited rate, and the validity period is 60s.
$timeout = 60;
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "PUT", $options);
Common::println("b.file speed limit upload url:".$signedUrl.PHP_EOL);
// Create a URL for speed-limited downloads, with a validity period of 120s.
$timeout = 120;
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "GET", $options);
Common::println("b.file speed limit download url:".$signedUrl.PHP_EOL);
//******************************* For complete usage, see the following functions ****************************************************
listObjects($ossClient, $bucket);
listObjectsV2($ossClient, $bucket);
listAllObjects($ossClient, $bucket);
createObjectDir($ossClient, $bucket);
putObject($ossClient, $bucket);
uploadFile($ossClient, $bucket);
getObject($ossClient, $bucket);
getObjectToLocalFile($ossClient, $bucket);
copyObject($ossClient, $bucket);
modifyMetaForObject($ossClient, $bucket);
getObjectMeta($ossClient, $bucket);
deleteObject($ossClient, $bucket);
deleteObjects($ossClient, $bucket);
doesObjectExist($ossClient, $bucket);
getSymlink($ossClient, $bucket);
putSymlink($ossClient, $bucket);
putObjectSpeed($ossClient, $bucket);
getObjectSpeed($ossClient, $bucket);
signUrlSpeedUpload($ossClient, $bucket);
signUrlSpeedDownload($ossClient, $bucket);
restoreObject($ossClient,$bucket);
/**
* Create a 'virtual' folder
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function createObjectDir($ossClient, $bucket)
{
try {
$ossClient->createObjectDir($bucket, "dir");
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Upload in-memory data to oss
*
* Simple upload---upload specified in-memory data to an OSS object
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function putObject($ossClient, $bucket)
{
$object = "oss-php-sdk-test/upload-test-object-name.txt";
$content = file_get_contents(__FILE__);
$options = array();
try {
$ossClient->putObject($bucket, $object, $content, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Uploads a local file to OSS
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function uploadFile($ossClient, $bucket)
{
$object = "oss-php-sdk-test/upload-test-object-name.txt";
$filePath = __FILE__;
$options = array();
try {
$ossClient->uploadFile($bucket, $object, $filePath, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Lists all files and folders in the bucket.
* Note if there's more items than the max-keys specified, the caller needs to use the nextMarker returned as the value for the next call's maker paramter.
* Loop through all the items returned from ListObjects.
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function listObjects($ossClient, $bucket)
{
$prefix = 'oss-php-sdk-test/';
$delimiter = '/';
$nextMarker = '';
$maxkeys = 1000;
$options = array(
'delimiter' => $delimiter,
'prefix' => $prefix,
'max-keys' => $maxkeys,
'marker' => $nextMarker,
);
try {
$listObjectInfo = $ossClient->listObjects($bucket, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
$objectList = $listObjectInfo->getObjectList(); // object list
$prefixList = $listObjectInfo->getPrefixList(); // directory list
if (!empty($objectList)) {
print("objectList:\n");
foreach ($objectList as $objectInfo) {
print($objectInfo->getKey() . "\n");
if($objectInfo->getOwner() != null){
printf("owner id:".$objectInfo->getOwner()->getId() . "\n");
printf("owner name:".$objectInfo->getOwner()->getDisplayName() . "\n");
}
}
}
if (!empty($prefixList)) {
print("prefixList: \n");
foreach ($prefixList as $prefixInfo) {
print($prefixInfo->getPrefix() . "\n");
}
}
}
/**
* Lists all files and folders in the bucket.
* Note if there's more items than the max-keys specified, the caller needs to use the nextMarker returned as the value for the next call's maker paramter.
* Loop through all the items returned from ListObjects.
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function listObjectsV2($ossClient, $bucket)
{
$prefix = 'oss-php-sdk-test/';
$delimiter = '/';
$maxkeys = 1000;
$options = array(
'delimiter' => $delimiter,
'prefix' => $prefix,
'max-keys' => $maxkeys,
'start-after' =>'test-object',
'fetch-owner' =>'true',
);
try {
$listObjectInfo = $ossClient->listObjectsV2($bucket, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
$objectList = $listObjectInfo->getObjectList(); // object list
$prefixList = $listObjectInfo->getPrefixList(); // directory list
if (!empty($objectList)) {
print("objectList:\n");
foreach ($objectList as $objectInfo) {
print($objectInfo->getKey() . "\n");
if($objectInfo->getOwner() != null){
printf("owner id:".$objectInfo->getOwner()->getId() . "\n");
printf("owner name:".$objectInfo->getOwner()->getDisplayName() . "\n");
}
}
}
if (!empty($prefixList)) {
print("prefixList: \n");
foreach ($prefixList as $prefixInfo) {
print($prefixInfo->getPrefix() . "\n");
}
}
}
/**
* Lists all folders and files under the bucket. Use nextMarker repeatedly to get all objects.
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function listAllObjects($ossClient, $bucket)
{
// Create dir/obj 'folder' and put some files into it.
for ($i = 0; $i < 100; $i += 1) {
$ossClient->putObject($bucket, "dir/obj" . strval($i), "hi");
$ossClient->createObjectDir($bucket, "dir/obj" . strval($i));
}
$prefix = 'dir/';
$delimiter = '/';
$nextMarker = '';
$maxkeys = 30;
while (true) {
$options = array(
'delimiter' => $delimiter,
'prefix' => $prefix,
'max-keys' => $maxkeys,
'marker' => $nextMarker,
);
var_dump($options);
try {
$listObjectInfo = $ossClient->listObjects($bucket, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
// Get the nextMarker, and it would be used as the next call's marker parameter to resume from the last call
$nextMarker = $listObjectInfo->getNextMarker();
$listObject = $listObjectInfo->getObjectList();
$listPrefix = $listObjectInfo->getPrefixList();
var_dump(count($listObject));
var_dump(count($listPrefix));
if ($nextMarker === '') {
break;
}
}
}
/**
* Get the content of an object.
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function getObject($ossClient, $bucket)
{
$object = "oss-php-sdk-test/upload-test-object-name.txt";
$options = array();
try {
$content = $ossClient->getObject($bucket, $object, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
if (file_get_contents(__FILE__) === $content) {
print(__FUNCTION__ . ": FileContent checked OK" . "\n");
} else {
print(__FUNCTION__ . ": FileContent checked FAILED" . "\n");
}
}
/**
* Put symlink
*
* @param OssClient $ossClient The Instance of OssClient
* @param string $bucket bucket name
* @return null
*/
function putSymlink($ossClient, $bucket)
{
$symlink = "test-samples-symlink";
$object = "test-samples-object";
try {
$ossClient->putObject($bucket, $object, 'test-content');
$ossClient->putSymlink($bucket, $symlink, $object);
$content = $ossClient->getObject($bucket, $symlink);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
if ($content == 'test-content') {
print(__FUNCTION__ . ": putSymlink checked OK" . "\n");
} else {
print(__FUNCTION__ . ": putSymlink checked FAILED" . "\n");
}
}
/**
* Get symlink
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function getSymlink($ossClient, $bucket)
{
$symlink = "test-samples-symlink";
$object = "test-samples-object";
try {
$ossClient->putObject($bucket, $object, 'test-content');
$ossClient->putSymlink($bucket, $symlink, $object);
$content = $ossClient->getSymlink($bucket, $symlink);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
if ($content[OssClient::OSS_SYMLINK_TARGET]) {
print(__FUNCTION__ . ": getSymlink checked OK" . "\n");
} else {
print(__FUNCTION__ . ": getSymlink checked FAILED" . "\n");
}
}
/**
* Get_object_to_local_file
*
* Get object
* Download object to a specified file.
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function getObjectToLocalFile($ossClient, $bucket)
{
$object = "oss-php-sdk-test/upload-test-object-name.txt";
$localfile = "upload-test-object-name.txt";
$options = array(
OssClient::OSS_FILE_DOWNLOAD => $localfile,
);
try {
$ossClient->getObject($bucket, $object, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK, please check localfile: 'upload-test-object-name.txt'" . "\n");
if (file_get_contents($localfile) === file_get_contents(__FILE__)) {
print(__FUNCTION__ . ": FileContent checked OK" . "\n");
} else {
print(__FUNCTION__ . ": FileContent checked FAILED" . "\n");
}
if (file_exists($localfile)) {
unlink($localfile);
}
}
/**
* Copy object
* When the source object is same as the target one, copy operation will just update the metadata.
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function copyObject($ossClient, $bucket)
{
$fromBucket = $bucket;
$fromObject = "oss-php-sdk-test/upload-test-object-name.txt";
$toBucket = $bucket;
$toObject = $fromObject . '.copy';
$options = array();
try {
$ossClient->copyObject($fromBucket, $fromObject, $toBucket, $toObject, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Update Object Meta
* it leverages the feature of copyObject when the source object is just the target object, the metadata could be updated via copy
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function modifyMetaForObject($ossClient, $bucket)
{
$fromBucket = $bucket;
$fromObject = "oss-php-sdk-test/upload-test-object-name.txt";
$toBucket = $bucket;
$toObject = $fromObject;
$copyOptions = array(
OssClient::OSS_HEADERS => array(
'Cache-Control' => 'max-age=60',
'Content-Disposition' => 'attachment; filename="xxxxxx"',
),
);
try {
$ossClient->copyObject($fromBucket, $fromObject, $toBucket, $toObject, $copyOptions);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Get object meta, that is, getObjectMeta
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function getObjectMeta($ossClient, $bucket)
{
$object = "oss-php-sdk-test/upload-test-object-name.txt";
try {
$objectMeta = $ossClient->getObjectMeta($bucket, $object);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
if (isset($objectMeta[strtolower('Content-Disposition')]) &&
'attachment; filename="xxxxxx"' === $objectMeta[strtolower('Content-Disposition')]
) {
print(__FUNCTION__ . ": ObjectMeta checked OK" . "\n");
} else {
print(__FUNCTION__ . ": ObjectMeta checked FAILED" . "\n");
}
}
/**
* Delete an object
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function deleteObject($ossClient, $bucket)
{
$object = "oss-php-sdk-test/upload-test-object-name.txt";
try {
$ossClient->deleteObject($bucket, $object);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Delete multiple objects in batch
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function deleteObjects($ossClient, $bucket)
{
$objects = array();
$objects[] = "oss-php-sdk-test/upload-test-object-name.txt";
$objects[] = "oss-php-sdk-test/upload-test-object-name.txt.copy";
try {
$ossClient->deleteObjects($bucket, $objects);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Check whether an object exists
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function doesObjectExist($ossClient, $bucket)
{
$object = "oss-php-sdk-test/upload-test-object-name.txt";
try {
$exist = $ossClient->doesObjectExist($bucket, $object);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
var_dump($exist);
}
/**
* Speed limit upload.
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function putObjectSpeed($ossClient, $bucket)
{
$object = "upload-test-object-name.txt";
$content = file_get_contents(__FILE__);
$options = array(
OssClient::OSS_HEADERS => array(
OssClient::OSS_TRAFFIC_LIMIT => 819200,
));
try {
$ossClient->putObject($bucket, $object, $content, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Speed limit download.
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function getObjectSpeed($ossClient, $bucket)
{
$object = "upload-test-object-name.txt";
$options = array(
OssClient::OSS_HEADERS => array(
OssClient::OSS_TRAFFIC_LIMIT => 819200,
));
try {
$ossClient->getObject($bucket, $object, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Speed limit download.
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function signUrlSpeedUpload($ossClient, $bucket)
{
$object = "upload-test-object-name.txt";
$timeout = 120;
$options = array(
OssClient::OSS_TRAFFIC_LIMIT => 819200,
);
$timeout = 60;
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "PUT", $options);
print($signedUrl);
}
/**
* Speed limit download.
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function signUrlSpeedDownload($ossClient, $bucket)
{
$object = "upload-test-object-name.txt";
$timeout = 120;
$options = array(
OssClient::OSS_TRAFFIC_LIMIT => 819200,
);
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "GET", $options);
print($signedUrl);
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Restore object
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
*/
function restoreObject($ossClient, $bucket)
{
$object = "oss-php-sdk-test/upload-test-object-name.txt";
$day = 3;
$tier = 'Expedited';
$config = new RestoreConfig($day,$tier);
$options = array(
OssClient::OSS_RESTORE_CONFIG => $config
);
try {
$ossClient->restoreObject($bucket, $object,$options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@@ -0,0 +1,366 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\OssClient;
use OSS\Core\OssException;
use OSS\Core\OssUtil;
use OSS\Model\TaggingConfig;
use OSS\Model\Tag;
$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//******************************* Simple usage ***************************************************************
// Upload Object add tag
$object = "b.file";
$options = array(
OssClient::OSS_HEADERS => array(
'x-oss-tagging' => 'key1=value1&key2=value2&key3=value3',
)
);
$result = $ossClient->putObject($bucket, $object, __FILE__,$options);
Common::println("b.file is created");
Common::println("tag is:".$result['oss-requestheaders']['x-oss-tagging']);
// Add object tags when uploading parts
$object = "b.file";
$file = __FILE__;
$options = array(
OssClient::OSS_CHECK_MD5 => true,
OssClient::OSS_PART_SIZE => 1,
OssClient::OSS_HEADERS => array(
'x-oss-tagging' => 'key1=value1&key2=value2&key3=value3',
),
);
$result = $ossClient->multiuploadFile($bucket, $object, $file, $options);
Common::println("b.file is created");
Common::println("tag is:".$result['oss-requestheaders']['x-oss-tagging']);
// get tags from object
$object = "a.txt";
$result = $ossClient->getObjectTagging($bucket,$object);
printf($object.'tags is: '.$result->serializeToXml().PHP_EOL);
// Add or change object tags to uploaded objects
$config = new TaggingConfig();
$config->addTag(new Tag("key1", "value1"));
$config->addTag(new Tag("key2", "value2"));
$ossClient->putObjectTagging($bucket, $object, $config);
// Add object tags when uploading
$object = "a.txt";
$filePath = "D:\\localpath\\b.txt";
$filePath1 = "D:\\localpath\\c.txt";
$options = array(
OssClient::OSS_HEADERS => array(
'x-oss-tagging' => 'key1=value1&key2=value2',
)
);
$position = $ossClient->appendObject($bucket, $object,'content one',0,$options);
printf('Content one append object Success'.PHP_EOL);
$position = $ossClient->appendObject($bucket, $object, 'content two',$position,$options);
printf('Content two append object Success'.PHP_EOL);
// delete tags
$object = "g.file";
$ossClient->deleteObjectTagging($bucket, $object);
printf($object.' tags has deleted'.PHP_EOL);
// Copy a small file
$fromBucket = $bucket;
$fromObject = "a.file";
$toBucket = $bucket;
$toObject = $fromObject . '.copy';
$options = array(
OssClient::OSS_HEADERS => array(
'x-oss-tagging-directive' => 'Replace',
'x-oss-tagging'=>'key1=value1&key2=value2&key3=value3',
));
$ossClient->copyObject($fromBucket, $fromObject, $toBucket, $toObject, $options);
$config = $ossClient->getObjectTagging($bucket, $toObject);
Common::println('object tags is:'.$config->serializeToXml());
// Copy a large file
$fromBucket = $bucket;
$fromObject = "a.file";
$toBucket = $bucket;
$toObject = $fromObject . '.copy';
$options = array(
OssClient::OSS_HEADERS => array(
'x-oss-tagging'=>'key1=value1&key2=value2&key3=value3',
));
$part_size = 256*1024*1024;
$objectMeta = $ossClient->getObjectMeta($fromBucket, $fromObject);
$length = $objectMeta['content-length'];
$upload_id = $ossClient->initiateMultipartUpload($toBucket, $toObject,$options);
$pieces = $ossClient->generateMultiuploadParts($length, $part_size);
$response_upload_part = array();
$copyId = 1;
$upload_position = 0;
foreach ($pieces as $i => $piece) {
$from_pos = $upload_position + (integer)$piece['seekTo'];
$to_pos = (integer)$piece['length'] + $from_pos - 1;
$up_options = array(
'start' => $from_pos,
'end' => $to_pos,
);
$response_upload_part[] = $ossClient->uploadPartCopy( $fromBucket, $fromObject, $toBucket, $toObject, $copyId, $upload_id, $up_options);
printf("initiateMultipartUpload, uploadPartCopy - part#{$copyId} OK\n");
$copyId = $copyId + 1;
}
$upload_parts = array();
foreach ($response_upload_part as $i => $etag) {
$upload_parts[] = array(
'PartNumber' => ($i + 1),
'ETag' => $etag,
);
}
$result = $ossClient->completeMultipartUpload($toBucket, $toObject, $upload_id, $upload_parts);
$config = $ossClient->getObjectTagging($bucket, $toObject);
Common::println($toObject.' tags is:'.$config->serializeToXml());
//******************************* For complete usage, see the following functions ****************************************************
putObject($ossClient,$bucket);
multiuploadFile($ossClient,$bucket);
appendObject($ossClient,$bucket);
putObjectTagging($ossClient,$bucket);
getObjectTagging($ossClient,$bucket);
deleteObjectTagging($ossClient,$bucket);
copyObjectSmall($ossClient,$bucket);
copyObjectLarge($ossClient,$bucket);
/**
* Upload Object add tag
* @param $ossClient OssClient
* @param $bucket bucket_name
*/
function putObject($ossClient,$bucket){
$object = "b.file";
$options = array(
OssClient::OSS_HEADERS => array(
'x-oss-tagging' => 'key1=value1&key2=value2&key3=value3',
));
try {
// 通过简单上传的方式上传Object。
$result = $ossClient->putObject($bucket, $object, __FILE__,$options);
Common::println("b.file is created".PHP_EOL);
Common::println("tag is:".$result['oss-requestheaders']['x-oss-tagging'].PHP_EOL);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Add object tags when uploading parts
* @param $ossClient OssClient
* @param $bucket bucket_name
*/
function multiuploadFile($ossClient,$bucket){
$object = "b.file";
$file = __FILE__;
$options = array(
OssClient::OSS_CHECK_MD5 => true,
OssClient::OSS_PART_SIZE => 1,
OssClient::OSS_HEADERS => array(
'x-oss-tagging' => 'key1=value1&key2=value2&key3=value3',
),
);
try {
$result = $ossClient->multiuploadFile($bucket, $object, $file, $options);
Common::println("b.file is created".PHP_EOL);
Common::println("tag is:".$result['oss-requestheaders']['x-oss-tagging'].PHP_EOL);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Add object tags when uploading
* @param $ossClient OssClient
* @param $bucket bucket_name string
*/
function appendObject($ossClient,$bucket){
$object = "g.file";
$content_array = array('Hello OSS', 'Hi OSS');
$options = array(
OssClient::OSS_HEADERS => array(
'x-oss-tagging' => 'key1=value1&key2=value2',
));
try {
$position = $ossClient->appendObject($bucket, $object, $content_array[0], 0, $options);
printf($content_array[0].' append object Success'.PHP_EOL);
$position = $ossClient->appendObject($bucket, $object, $content_array[1], $position);
printf($content_array[1].' append object Success'.PHP_EOL);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* @param $ossClient OssClient
* @param $bucket bucket_name string
* @throws OssException
*/
function putObjectTagging($ossClient,$bucket){
$object = "g.file";
$config = new TaggingConfig();
$config->addTag(new Tag("key1", "value1"));
$config->addTag(new Tag("key2", "value2"));
try {
$ossClient->putObjectTagging($bucket, $object, $config);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* get object tags
* @param $ossClient OssClient
* @param $bucket bucket_name string
*/
function getObjectTagging($ossClient,$bucket){
$object = "g.file";
try {
$config = $ossClient->getObjectTagging($bucket, $object);
printf($object." tags is:".$config->serializeToXml().PHP_EOL);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* get object tags
* @param $ossClient OssClient
* @param $bucket bucket_name string
*/
function deleteObjectTagging($ossClient,$bucket){
$object = "g.file";
try {
$ossClient->deleteObjectTagging($bucket, $object);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Copy small files
* @param $ossClient OssClient
* @param $bucket bucket_name string
*/
function copyObjectSmall($ossClient,$bucket){
$fromBucket = $bucket;
$fromObject = "a.file";
$toBucket = $bucket;
$toObject = $fromObject . '.copy';
$options = array(
OssClient::OSS_HEADERS => array(
'x-oss-tagging-directive' => 'Replace',
'x-oss-tagging'=>'key1=value1&key2=value2&key3=value3',
));
try {
$ossClient->copyObject($fromBucket, $fromObject, $toBucket, $toObject, $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
$config = $ossClient->getObjectTagging($bucket, $toObject);
Common::println('object tags is:'.$config->serializeToXml());
print(__FUNCTION__ . ": OK" . "\n");
}
/**
* Copy a large file
* @param $ossClient OssClient
* @param $bucket bucket_name string
*/
function copyObjectLarge($ossClient,$bucket){
$fromBucket = $bucket;
$fromObject = "a.file";
$toBucket = $bucket;
$toObject = $fromObject . '.copy';
$options = array(
OssClient::OSS_HEADERS => array(
'x-oss-tagging'=>'key1=value1&key2=value2&key3=value3',
));
$part_size = 256*1024*1024;
try{
$objectMeta = $ossClient->getObjectMeta($fromBucket, $fromObject);
$length = $objectMeta['content-length'];
$upload_id = $ossClient->initiateMultipartUpload($toBucket, $toObject,$options);
$pieces = $ossClient->generateMultiuploadParts($length, $part_size);
$response_upload_part = array();
$copyId = 1;
$upload_position = 0;
foreach ($pieces as $i => $piece) {
$from_pos = $upload_position + (integer)$piece['seekTo'];
$to_pos = (integer)$piece['length'] + $from_pos - 1;
$up_options = array(
'start' => $from_pos,
'end' => $to_pos,
);
$response_upload_part[] = $ossClient->uploadPartCopy( $fromBucket, $fromObject, $toBucket, $toObject, $copyId, $upload_id, $up_options);
printf("initiateMultipartUpload, uploadPartCopy - part#{$copyId} OK\n");
$copyId = $copyId + 1;
}
$upload_parts = array();
foreach ($response_upload_part as $i => $etag) {
$upload_parts[] = array(
'PartNumber' => ($i + 1),
'ETag' => $etag,
);
}
$result = $ossClient->completeMultipartUpload($toBucket, $toObject, $upload_id, $upload_parts);
printf('copy success'. "\n");
} catch(OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
$config = $ossClient->getObjectTagging($bucket, $toObject);
Common::println($toObject.' tags is:'.$config->serializeToXml());
print(__FUNCTION__ . ": OK" . "\n");
}

View File

@@ -0,0 +1,13 @@
<?php
error_reporting(E_ALL | E_NOTICE);
require_once __DIR__ . '/Bucket.php';
require_once __DIR__ . '/BucketCors.php';
require_once __DIR__ . '/BucketLifecycle.php';
require_once __DIR__ . '/BucketReferer.php';
require_once __DIR__ . '/BucketLogging.php';
require_once __DIR__ . '/BucketWebsite.php';
require_once __DIR__ . '/Signature.php';
require_once __DIR__ . '/Object1.php';
require_once __DIR__ . '/MultipartUpload.php';

View File

@@ -0,0 +1,142 @@
<?php
require_once __DIR__ . '/Common.php';
use OSS\Http\RequestCore;
use OSS\Http\ResponseCore;
use OSS\OssClient;
use OSS\Core\OssException;
$bucket = Common::getBucketName();
$ossClient = Common::getOssClient();
if (is_null($ossClient)) exit(1);
//******************************* Simple Usage ***************************************************************
$ossClient->uploadFile($bucket, "a.file", __FILE__);
// Generate a signed url for getting an object. The URL can be used in browser directly to download the file.
$signedUrl = $ossClient->signUrl($bucket, "a.file", 3600);
Common::println($signedUrl);
// Generate the signed url for putting an object. User can use put method with this url to upload a file to "a.file".
$signedUrl = $ossClient->signUrl($bucket, "a.file", "3600", "PUT");
Common::println($signedUrl);
// Generate the signed url for putting an object from local file. The url can be used directly to upload the file to "a.file".
$signedUrl = $ossClient->signUrl($bucket, "a.file", 3600, "PUT", array('Content-Type' => 'txt'));
Common::println($signedUrl);
//******************************* For complete usage, see the following functions ****************************************************
getSignedUrlForPuttingObject($ossClient, $bucket);
getSignedUrlForPuttingObjectFromFile($ossClient, $bucket);
getSignedUrlForGettingObject($ossClient, $bucket);
/**
* Generate the signed url for getObject() to control read accesses under private privilege
*
* @param $ossClient OssClient OssClient instance
* @param $bucket string bucket name
* @return null
*/
function getSignedUrlForGettingObject($ossClient, $bucket)
{
$object = "test/test-signature-test-upload-and-download.txt";
$timeout = 3600;
try {
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": signedUrl: " . $signedUrl . "\n");
/**
* Use similar code to access the object by url, or use browser to access the object.
*/
$request = new RequestCore($signedUrl);
$request->set_method('GET');
$request->add_header('Content-Type', '');
$request->send_request();
$res = new ResponseCore($request->get_response_header(), $request->get_response_body(), $request->get_response_code());
if ($res->isOK()) {
print(__FUNCTION__ . ": OK" . "\n");
} else {
print(__FUNCTION__ . ": FAILED" . "\n");
};
}
/**
* Generate the signed url for PutObject to control write accesses under private privilege.
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @return null
* @throws OssException
*/
function getSignedUrlForPuttingObject($ossClient, $bucket)
{
$object = "test/test-signature-test-upload-and-download.txt";
$timeout = 3600;
$options = NULL;
try {
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "PUT");
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": signedUrl: " . $signedUrl . "\n");
$content = file_get_contents(__FILE__);
$request = new RequestCore($signedUrl);
$request->set_method('PUT');
$request->add_header('Content-Type', '');
$request->add_header('Content-Length', strlen($content));
$request->set_body($content);
$request->send_request();
$res = new ResponseCore($request->get_response_header(),
$request->get_response_body(), $request->get_response_code());
if ($res->isOK()) {
print(__FUNCTION__ . ": OK" . "\n");
} else {
print(__FUNCTION__ . ": FAILED" . "\n");
};
}
/**
* Generate the signed url for PutObject's signed url. User could use the signed url to upload file directly.
*
* @param OssClient $ossClient OssClient instance
* @param string $bucket bucket name
* @throws OssException
*/
function getSignedUrlForPuttingObjectFromFile($ossClient, $bucket)
{
$file = __FILE__;
$object = "test/test-signature-test-upload-and-download.txt";
$timeout = 3600;
$options = array('Content-Type' => 'txt');
try {
$signedUrl = $ossClient->signUrl($bucket, $object, $timeout, "PUT", $options);
} catch (OssException $e) {
printf(__FUNCTION__ . ": FAILED\n");
printf($e->getMessage() . "\n");
return;
}
print(__FUNCTION__ . ": signedUrl: " . $signedUrl . "\n");
$request = new RequestCore($signedUrl);
$request->set_method('PUT');
$request->add_header('Content-Type', 'txt');
$request->set_read_file($file);
$request->set_read_stream_size(sprintf('%u',filesize($file)));
$request->send_request();
$res = new ResponseCore($request->get_response_header(),
$request->get_response_body(), $request->get_response_code());
if ($res->isOK()) {
print(__FUNCTION__ . ": OK" . "\n");
} else {
print(__FUNCTION__ . ": FAILED" . "\n");
};
}