BucketOperationsSample.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503
  1. <?php
  2. /**
  3. * Copyright 2019 Huawei Technologies Co.,Ltd.
  4. * Licensed under the Apache License, Version 2.0 (the "License"); you may not use
  5. * this file except in compliance with the License. You may obtain a copy of the
  6. * License at
  7. *
  8. * http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. * Unless required by applicable law or agreed to in writing, software distributed
  11. * under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
  12. * CONDITIONS OF ANY KIND, either express or implied. See the License for the
  13. * specific language governing permissions and limitations under the License.
  14. *
  15. */
  16. /**
  17. * This sample demonstrates how to do bucket-related operations
  18. * (such as do bucket ACL/CORS/Lifecycle/Logging/Website/Location/Tagging/OPTIONS)
  19. * on OBS using the OBS SDK for PHP.
  20. */
  21. if (file_exists ( 'vendor/autoload.php' )) {
  22. require 'vendor/autoload.php';
  23. } else {
  24. require '../vendor/autoload.php'; // sample env
  25. }
  26. if (file_exists ( 'obs-autoloader.php' )) {
  27. require 'obs-autoloader.php';
  28. } else {
  29. require '../obs-autoloader.php'; // sample env
  30. }
  31. use Obs\ObsClient;
  32. use Obs\ObsException;
  33. use function GuzzleHttp\json_encode;
  34. $ak = '*** Provide your Access Key ***';
  35. $sk = '*** Provide your Secret Key ***';
  36. $endpoint = 'https://your-endpoint:443';
  37. $bucketName = 'my-obs-bucket-demo';
  38. /*
  39. * Constructs a obs client instance with your account for accessing OBS
  40. */
  41. $obsClient = ObsClient::factory ( [
  42. 'key' => $ak,
  43. 'secret' => $sk,
  44. 'endpoint' => $endpoint,
  45. 'socket_timeout' => 30,
  46. 'connect_timeout' => 10
  47. ] );
  48. try {
  49. /*
  50. * Put bucket operation
  51. */
  52. createBucket ();
  53. /*
  54. * Get bucket location operation
  55. */
  56. getBucketLocation ();
  57. /*
  58. * Get bucket storageInfo operation
  59. */
  60. getBucketStorageInfo ();
  61. /*
  62. * Put/Get bucket quota operations
  63. */
  64. doBucketQuotaOperation ();
  65. /*
  66. * Put/Get bucket versioning operations
  67. */
  68. doBucketVersioningOperation ();
  69. /*
  70. * Put/Get bucket acl operations
  71. */
  72. $ownerId = doBucketAclOperation ();
  73. /*
  74. * Put/Get/Delete bucket cors operations
  75. */
  76. doBucketCorsOperation ();
  77. /*
  78. * Options bucket operation
  79. */
  80. optionsBucket ();
  81. /*
  82. * Get bucket metadata operation
  83. */
  84. getBucketMetadata ();
  85. /*
  86. * Put/Get/Delete bucket lifecycle operations
  87. */
  88. doBucketLifecycleOperation ();
  89. /*
  90. * Put/Get/Delete bucket logging operations
  91. */
  92. doBucketLoggingOperation ($ownerId);
  93. /*
  94. * Put/Get/Delete bucket website operations
  95. */
  96. doBucketWebsiteOperation ();
  97. /*
  98. * Put/Get/Delete bucket tagging operations
  99. */
  100. doBucketTaggingOperation ();
  101. /*
  102. * Delete bucket operation
  103. */
  104. deleteBucket ();
  105. } catch ( ObsException $e ) {
  106. echo 'Response Code:' . $e->getStatusCode () . PHP_EOL;
  107. echo 'Error Message:' . $e->getExceptionMessage () . PHP_EOL;
  108. echo 'Error Code:' . $e->getExceptionCode () . PHP_EOL;
  109. echo 'Request ID:' . $e->getRequestId () . PHP_EOL;
  110. echo 'Exception Type:' . $e->getExceptionType () . PHP_EOL;
  111. } finally{
  112. $obsClient->close ();
  113. }
  114. function createBucket()
  115. {
  116. global $obsClient;
  117. global $bucketName;
  118. $resp = $obsClient->createBucket ([
  119. 'Bucket' => $bucketName,
  120. ]);
  121. printf("HttpStatusCode:%s\n\n", $resp ['HttpStatusCode']);
  122. printf("Create bucket: %s successfully!\n\n", $bucketName);
  123. }
  124. function getBucketLocation()
  125. {
  126. global $obsClient;
  127. global $bucketName;
  128. $promise = $obsClient -> getBucketLocationAsync(['Bucket' => $bucketName], function($exception, $resp){
  129. printf("Getting bucket location %s\n\n", $resp ['Location']);
  130. });
  131. $promise -> wait();
  132. }
  133. function getBucketStorageInfo()
  134. {
  135. global $obsClient;
  136. global $bucketName;
  137. $promise = $obsClient -> getBucketStorageInfoAsync(['Bucket' => $bucketName], function($exception, $resp){
  138. printf("Getting bucket storageInfo Size:%d,ObjectNumber:%d\n\n", $resp ['Size'], $resp ['ObjectNumber']);
  139. });
  140. $promise -> wait();
  141. }
  142. function doBucketQuotaOperation()
  143. {
  144. global $obsClient;
  145. global $bucketName;
  146. $obsClient->setBucketQuota ([
  147. 'Bucket' => $bucketName,
  148. 'StorageQuota' => 1024 * 1024 * 1024//Set bucket quota to 1GB
  149. ]);
  150. $resp = $obsClient->getBucketQuota ([
  151. 'Bucket' => $bucketName
  152. ]);
  153. printf ("Getting bucket quota:%s\n\n", $resp ['StorageQuota'] );
  154. }
  155. function doBucketVersioningOperation()
  156. {
  157. global $obsClient;
  158. global $bucketName;
  159. $resp = $obsClient->getBucketVersioningConfiguration ( [
  160. 'Bucket' => $bucketName
  161. ]);
  162. printf ( "Getting bucket versioning config:%s\n\n", $resp ['Status']);
  163. //Enable bucket versioning
  164. $obsClient->setBucketVersioningConfiguration ([
  165. 'Bucket' => $bucketName,
  166. 'Status' => 'Enabled'
  167. ]);
  168. $resp = $obsClient->getBucketVersioningConfiguration ( [
  169. 'Bucket' => $bucketName
  170. ]);
  171. printf ( "Current bucket versioning config:%s\n\n", $resp ['Status']);
  172. //Suspend bucket versioning
  173. $obsClient->setBucketVersioningConfiguration ([
  174. 'Bucket' => $bucketName,
  175. 'Status' => 'Suspended'
  176. ]);
  177. $resp = $obsClient->getBucketVersioningConfiguration ( [
  178. 'Bucket' => $bucketName
  179. ]);
  180. printf ( "Current bucket versioning config:%s\n\n", $resp ['Status']);
  181. }
  182. function doBucketAclOperation()
  183. {
  184. global $obsClient;
  185. global $bucketName;
  186. printf ("Setting bucket ACL to ". ObsClient::AclPublicRead. "\n\n");
  187. $obsClient->setBucketAcl ([
  188. 'Bucket' => $bucketName,
  189. 'ACL' => ObsClient::AclPublicRead,
  190. ]);
  191. $resp = $obsClient->getBucketAcl ([
  192. 'Bucket' => $bucketName
  193. ]);
  194. printf ("Getting bucket ACL:%s\n\n", json_encode($resp -> toArray()));
  195. printf ("Setting bucket ACL to ". ObsClient::AclPrivate. "\n\n");
  196. $obsClient->setBucketAcl ([
  197. 'Bucket' => $bucketName,
  198. 'ACL' => ObsClient::AclPrivate,
  199. ]);
  200. $resp = $obsClient->getBucketAcl ([
  201. 'Bucket' => $bucketName
  202. ]);
  203. printf ("Getting bucket ACL:%s\n\n", json_encode($resp -> toArray()));
  204. return $resp ['Owner'] ['ID'];
  205. }
  206. function doBucketCorsOperation()
  207. {
  208. global $obsClient;
  209. global $bucketName;
  210. printf ("Setting bucket CORS\n\n");
  211. $obsClient->setBucketCors ( [
  212. 'Bucket' => $bucketName,
  213. 'CorsRule' => [
  214. [
  215. 'AllowedMethod' => ['HEAD', 'GET', 'PUT'],
  216. 'AllowedOrigin' => ['http://www.a.com', 'http://www.b.com'],
  217. 'AllowedHeader'=> ['Authorization'],
  218. 'ExposeHeaders' => ['x-obs-test1', 'x-obs-test2'],
  219. 'MaxAgeSeconds' => 100
  220. ]
  221. ]
  222. ] );
  223. printf ("Getting bucket CORS:%s\n\n", json_encode($obsClient-> getBucketCors(['Bucket' => $bucketName])-> toArray()));
  224. }
  225. function optionsBucket()
  226. {
  227. global $obsClient;
  228. global $bucketName;
  229. $resp = $obsClient->optionsBucket([
  230. 'Bucket'=>$bucketName,
  231. 'Origin'=>'http://www.a.com',
  232. 'AccessControlRequestMethods' => ['PUT'],
  233. 'AccessControlRequestHeaders'=> ['Authorization']
  234. ]);
  235. printf ("Options bucket: %s\n\n", json_encode($resp -> toArray()));
  236. }
  237. function getBucketMetadata()
  238. {
  239. global $obsClient;
  240. global $bucketName;
  241. printf ("Getting bucket metadata\n\n");
  242. $resp = $obsClient->getBucketMetadata ( [
  243. "Bucket" => $bucketName,
  244. "Origin" => "http://www.a.com",
  245. "RequestHeader" => "Authorization"
  246. ] );
  247. printf ( "\tHttpStatusCode:%s\n", $resp ['HttpStatusCode'] );
  248. printf ( "\tStorageClass:%s\n", $resp ["StorageClass"] );
  249. printf ( "\tAllowOrigin:%s\n", $resp ["AllowOrigin"] );
  250. printf ( "\tMaxAgeSeconds:%s\n", $resp ["MaxAgeSeconds"] );
  251. printf ( "\tExposeHeader:%s\n", $resp ["ExposeHeader"] );
  252. printf ( "\tAllowHeader:%s\n", $resp ["AllowHeader"] );
  253. printf ( "\tAllowMethod:%s\n", $resp ["AllowMethod"] );
  254. printf ("Deleting bucket CORS\n\n");
  255. $obsClient -> deleteBucketCors(['Bucket' => $bucketName]);
  256. }
  257. function doBucketLifecycleOperation()
  258. {
  259. global $obsClient;
  260. global $bucketName;
  261. $ruleId0 = "delete obsoleted files";
  262. $matchPrefix0 = "obsoleted/";
  263. $ruleId1 = "delete temporary files";
  264. $matchPrefix1 = "temporary/";
  265. $ruleId2 = "delete temp files";
  266. $matchPrefix2 = "temp/";
  267. printf ("Setting bucket lifecycle\n\n");
  268. $obsClient->setBucketLifecycleConfiguration ( [
  269. 'Bucket' => $bucketName,
  270. 'Rules' => [
  271. [
  272. 'ID' => $ruleId0,
  273. 'Prefix' => $matchPrefix0,
  274. 'Status' => 'Enabled',
  275. 'Expiration'=> ['Days'=>5]
  276. ],
  277. [
  278. 'ID' => $ruleId1,
  279. 'Prefix' => $matchPrefix1,
  280. 'Status' => 'Enabled',
  281. 'Expiration' => ['Date' => '2017-12-31T00:00:00Z']
  282. ],
  283. [
  284. 'ID' => $ruleId2,
  285. 'Prefix' => $matchPrefix2,
  286. 'Status' => 'Enabled',
  287. 'NoncurrentVersionExpiration' => ['NoncurrentDays' => 10]
  288. ]
  289. ]
  290. ]);
  291. printf ("Getting bucket lifecycle\n\n");
  292. $resp = $obsClient->getBucketLifecycleConfiguration ([
  293. 'Bucket' => $bucketName
  294. ]);
  295. $i = 0;
  296. foreach ( $resp ['Rules'] as $rule ) {
  297. printf ( "\tRules[$i][Expiration][Date]:%s,Rules[$i][Expiration][Days]:%d\n", $rule ['Expiration'] ['Date'], $rule ['Expiration'] ['Days'] );
  298. printf ( "\yRules[$i][NoncurrentVersionExpiration][NoncurrentDays]:%s\n", $rule ['NoncurrentVersionExpiration'] ['NoncurrentDays'] );
  299. printf ( "\tRules[$i][ID]:%s,Rules[$i][Prefix]:%s,Rules[$i][Status]:%s\n", $rule ['ID'], $rule ['Prefix'], $rule ['Status'] );
  300. $i ++;
  301. }
  302. printf ("Deleting bucket lifecycle\n\n");
  303. $obsClient->deleteBucketLifecycleConfiguration (['Bucket' => $bucketName]);
  304. }
  305. function doBucketLoggingOperation($ownerId)
  306. {
  307. global $obsClient;
  308. global $bucketName;
  309. printf ("Setting bucket ACL, give the log-delivery group " . ObsClient::PermissionWrite ." and " .ObsClient::PermissionReadAcp ." permissions\n\n");
  310. $obsClient->setBucketAcl ([
  311. 'Bucket' => $bucketName,
  312. 'Owner' => [
  313. 'ID' => $ownerId
  314. ],
  315. 'Grants' => [
  316. [
  317. 'Grantee' => [
  318. 'URI' => ObsClient::GroupLogDelivery,
  319. 'Type' => 'Group'
  320. ],
  321. 'Permission' => ObsClient::PermissionWrite
  322. ],
  323. [
  324. 'Grantee' => [
  325. 'URI' => ObsClient::GroupLogDelivery,
  326. 'Type' => 'Group'
  327. ],
  328. 'Permission' => ObsClient::PermissionReadAcp
  329. ],
  330. ]
  331. ]);
  332. printf ("Setting bucket logging\n\n");
  333. $targetBucket = $bucketName;
  334. $targetPrefix = 'log-';
  335. $obsClient->setBucketLoggingConfiguration ( [
  336. 'Bucket' => $bucketName,
  337. 'LoggingEnabled' => [
  338. 'TargetBucket' => $targetBucket,
  339. 'TargetPrefix' => $targetPrefix,
  340. 'TargetGrants' => [
  341. [
  342. 'Grantee' => [
  343. 'URI' => ObsClient::GroupAuthenticatedUsers,
  344. 'Type' => 'Group'
  345. ],
  346. 'Permission' => ObsClient::PermissionRead
  347. ]
  348. ]
  349. ]
  350. ]);
  351. printf ("Getting bucket logging\n");
  352. $resp = $obsClient->getBucketLoggingConfiguration ([
  353. 'Bucket' => $bucketName
  354. ]);
  355. printf ("\tTarget bucket=%s, target prefix=%s\n", $resp ['LoggingEnabled'] ['TargetBucket'], $resp ['LoggingEnabled'] ['TargetPrefix'] );
  356. printf("\tTargetGrants=%s\n\n", json_encode($resp ['LoggingEnabled'] ['TargetGrants']));
  357. printf ("Deletting bucket logging\n");
  358. $obsClient->setBucketLoggingConfiguration ( [
  359. 'Bucket' => $bucketName
  360. ]);
  361. }
  362. function doBucketWebsiteOperation()
  363. {
  364. global $obsClient;
  365. global $bucketName;
  366. printf ("Setting bucket website\n\n");
  367. $obsClient->setBucketWebsiteConfiguration ([
  368. 'Bucket' => $bucketName,
  369. 'IndexDocument' => [
  370. 'Suffix' => 'index.html'
  371. ],
  372. 'ErrorDocument' => [
  373. 'Key' => 'error.html'
  374. ]
  375. ]);
  376. printf ("Getting bucket website\n");
  377. $resp = $obsClient->GetBucketWebsiteConfiguration ( [
  378. 'Bucket' => $bucketName
  379. ]);
  380. printf ("\tIndex document=%s, error document=%s\n\n", $resp ['IndexDocument'] ['Suffix'], $resp ['ErrorDocument'] ['Key']);
  381. printf ("Deletting bucket website\n");
  382. $obsClient->deleteBucketWebsiteConfiguration ([
  383. 'Bucket' => $bucketName
  384. ]);
  385. }
  386. function doBucketTaggingOperation()
  387. {
  388. global $obsClient;
  389. global $bucketName;
  390. printf ("Setting bucket tagging\n\n");
  391. $obsClient -> setBucketTagging([
  392. 'Bucket' => $bucketName,
  393. 'TagSet' => [
  394. [
  395. 'Key' => 'testKey1',
  396. 'Value' => 'testValue1'
  397. ],
  398. [
  399. 'Key' => 'testKey2',
  400. 'Value' => 'testValue2'
  401. ]
  402. ]
  403. ]);
  404. printf ("Getting bucket tagging\n");
  405. $resp = $obsClient -> getBucketTagging(['Bucket' => $bucketName]);
  406. printf ("\t%s\n\n", json_encode($resp->toArray()));
  407. printf ("Deletting bucket tagging\n\n");
  408. $obsClient -> deleteBucketTagging(['Bucket' => $bucketName]);
  409. }
  410. function deleteBucket()
  411. {
  412. global $obsClient;
  413. global $bucketName;
  414. $resp = $obsClient->deleteBucket ([
  415. 'Bucket' => $bucketName
  416. ] );
  417. printf("Deleting bucket %s successfully!\n\n", $bucketName);
  418. printf("HttpStatusCode:%s\n\n", $resp ['HttpStatusCode']);
  419. }