PageRenderTime 57ms CodeModel.GetById 22ms RepoModel.GetById 0ms app.codeStats 0ms

/articles/storage/storage-php-how-to-use-blobs.md

https://gitlab.com/apachipa/azure-content
Markdown | 309 lines | 216 code | 93 blank | 0 comment | 0 complexity | af8a7fb41e5248becf2874d780e0df7b MD5 | raw file
  1. <properties
  2. pageTitle="How to use blob storage (object storage) from PHP | Microsoft Azure"
  3. description="Store unstructured data in the cloud with Azure Blob storage (object storage)."
  4. documentationCenter="php"
  5. services="storage"
  6. authors="allclark"
  7. manager="douge"
  8. editor=""/>
  9. <tags
  10. ms.service="storage"
  11. ms.workload="storage"
  12. ms.tgt_pltfrm="na"
  13. ms.devlang="PHP"
  14. ms.topic="article"
  15. ms.date="06/01/2016"
  16. ms.author="allclark;yaqiyang"/>
  17. # How to use blob storage from PHP
  18. [AZURE.INCLUDE [storage-selector-blob-include](../../includes/storage-selector-blob-include.md)]
  19. ## Overview
  20. Azure Blob storage is a service that stores unstructured data in the cloud as objects/blobs. Blob storage can store any type of text or binary data, such as a document, media file, or application installer. Blob storage is also referred to as object storage.
  21. This guide shows you how to perform common scenarios using the Azure blob service. The samples are written in PHP and use the [Azure SDK for PHP] [download]. The scenarios covered include **uploading**, **listing**, **downloading**, and **deleting** blobs. For more information on blobs, see the [Next steps](#next-steps) section.
  22. [AZURE.INCLUDE [storage-blob-concepts-include](../../includes/storage-blob-concepts-include.md)]
  23. [AZURE.INCLUDE [storage-create-account-include](../../includes/storage-create-account-include.md)]
  24. ## Create a PHP application
  25. The only requirement for creating a PHP application that accesses the Azure blob service is the referencing of classes in the Azure SDK for PHP from within your code. You can use any development tools to create your application, including Notepad.
  26. In this guide, you use service features, which can be called within a PHP application locally or in code running within an Azure web role, worker role, or website.
  27. ## Get the Azure Client Libraries
  28. [AZURE.INCLUDE [get-client-libraries](../../includes/get-client-libraries.md)]
  29. ## Configure your application to access the blob service
  30. To use the Azure blob service APIs, you need to:
  31. 1. Reference the autoloader file using the [require_once] statement, and
  32. 2. Reference any classes you might use.
  33. The following example shows how to include the autoloader file and reference the **ServicesBuilder** class.
  34. > [AZURE.NOTE] This example (and other examples in this article) assume you have installed the PHP Client Libraries for Azure via Composer. If you installed the libraries manually, you need to reference the `WindowsAzure.php` autoloader file.
  35. require_once 'vendor/autoload.php';
  36. use WindowsAzure\Common\ServicesBuilder;
  37. In the examples below, the `require_once` statement will be shown always, but only the classes necessary for the example to execute are referenced.
  38. ## Set up an Azure storage connection
  39. To instantiate an Azure blob service client, you must first have a valid connection string. The format for the blob service connection string is:
  40. For accessing a live service:
  41. DefaultEndpointsProtocol=[http|https];AccountName=[yourAccount];AccountKey=[yourKey]
  42. For accessing the storage emulator:
  43. UseDevelopmentStorage=true
  44. To create any Azure service client, you need to use the **ServicesBuilder** class. You can:
  45. * Pass the connection string directly to it or
  46. * Use the **CloudConfigurationManager (CCM)** to check multiple external sources for the connection string:
  47. * By default, it comes with support for one external source - environmental variables.
  48. * You can add new sources by extending the **ConnectionStringSource** class.
  49. For the examples outlined here, the connection string will be passed directly.
  50. require_once 'vendor/autoload.php';
  51. use WindowsAzure\Common\ServicesBuilder;
  52. $blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);
  53. ## Create a container
  54. [AZURE.INCLUDE [storage-container-naming-rules-include](../../includes/storage-container-naming-rules-include.md)]
  55. A **BlobRestProxy** object lets you create a blob container with the **createContainer** method. When creating a container, you can set options on the container, but doing so is not required. (The example below shows how to set the container access control list (ACL) and container metadata.)
  56. require_once 'vendor\autoload.php';
  57. use WindowsAzure\Common\ServicesBuilder;
  58. use MicrosoftAzure\Storage\Blob\Models\CreateContainerOptions;
  59. use MicrosoftAzure\Storage\Blob\Models\PublicAccessType;
  60. use MicrosoftAzure\Storage\Common\ServiceException;
  61. // Create blob REST proxy.
  62. $blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);
  63. // OPTIONAL: Set public access policy and metadata.
  64. // Create container options object.
  65. $createContainerOptions = new CreateContainerOptions();
  66. // Set public access policy. Possible values are
  67. // PublicAccessType::CONTAINER_AND_BLOBS and PublicAccessType::BLOBS_ONLY.
  68. // CONTAINER_AND_BLOBS:
  69. // Specifies full public read access for container and blob data.
  70. // proxys can enumerate blobs within the container via anonymous
  71. // request, but cannot enumerate containers within the storage account.
  72. //
  73. // BLOBS_ONLY:
  74. // Specifies public read access for blobs. Blob data within this
  75. // container can be read via anonymous request, but container data is not
  76. // available. proxys cannot enumerate blobs within the container via
  77. // anonymous request.
  78. // If this value is not specified in the request, container data is
  79. // private to the account owner.
  80. $createContainerOptions->setPublicAccess(PublicAccessType::CONTAINER_AND_BLOBS);
  81. // Set container metadata.
  82. $createContainerOptions->addMetaData("key1", "value1");
  83. $createContainerOptions->addMetaData("key2", "value2");
  84. try {
  85. // Create container.
  86. $blobRestProxy->createContainer("mycontainer", $createContainerOptions);
  87. }
  88. catch(ServiceException $e){
  89. // Handle exception based on error codes and messages.
  90. // Error codes and messages are here:
  91. // http://msdn.microsoft.com/library/azure/dd179439.aspx
  92. $code = $e->getCode();
  93. $error_message = $e->getMessage();
  94. echo $code.": ".$error_message."<br />";
  95. }
  96. Calling **setPublicAccess(PublicAccessType::CONTAINER\_AND\_BLOBS)** makes the container and blob data accessible via anonymous requests. Calling **setPublicAccess(PublicAccessType::BLOBS_ONLY)** makes only blob data accessible via anonymous requests. For more information about container ACLs, see [Set container ACL (REST API)][container-acl].
  97. For more information about Blob service error codes, see [Blob Service Error Codes][error-codes].
  98. ## Upload a blob into a container
  99. To upload a file as a blob, use the **BlobRestProxy->createBlockBlob** method. This operation creates the blob if it doesn't exist, or overwrites it if it does. The code example below assumes that the container has already been created and uses [fopen][fopen] to open the file as a stream.
  100. require_once 'vendor/autoload.php';
  101. use WindowsAzure\Common\ServicesBuilder;
  102. use MicrosoftAzure\Storage\Common\ServiceException;
  103. // Create blob REST proxy.
  104. $blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);
  105. $content = fopen("c:\myfile.txt", "r");
  106. $blob_name = "myblob";
  107. try {
  108. //Upload blob
  109. $blobRestProxy->createBlockBlob("mycontainer", $blob_name, $content);
  110. }
  111. catch(ServiceException $e){
  112. // Handle exception based on error codes and messages.
  113. // Error codes and messages are here:
  114. // http://msdn.microsoft.com/library/azure/dd179439.aspx
  115. $code = $e->getCode();
  116. $error_message = $e->getMessage();
  117. echo $code.": ".$error_message."<br />";
  118. }
  119. Note that the previous sample uploads a blob as a stream. However, a blob can also be uploaded as a string using, for example, the [file\_get\_contents][file_get_contents] function. To do this using the previous sample, change `$content = fopen("c:\myfile.txt", "r");` to `$content = file_get_contents("c:\myfile.txt");`.
  120. ## List the blobs in a container
  121. To list the blobs in a container, use the **BlobRestProxy->listBlobs** method with a **foreach** loop to loop through the result. The following code displays the name of each blob as output in a container and displays its URI to the browser.
  122. require_once 'vendor/autoload.php';
  123. use WindowsAzure\Common\ServicesBuilder;
  124. use MicrosoftAzure\Storage\Common\ServiceException;
  125. // Create blob REST proxy.
  126. $blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);
  127. try {
  128. // List blobs.
  129. $blob_list = $blobRestProxy->listBlobs("mycontainer");
  130. $blobs = $blob_list->getBlobs();
  131. foreach($blobs as $blob)
  132. {
  133. echo $blob->getName().": ".$blob->getUrl()."<br />";
  134. }
  135. }
  136. catch(ServiceException $e){
  137. // Handle exception based on error codes and messages.
  138. // Error codes and messages are here:
  139. // http://msdn.microsoft.com/library/azure/dd179439.aspx
  140. $code = $e->getCode();
  141. $error_message = $e->getMessage();
  142. echo $code.": ".$error_message."<br />";
  143. }
  144. ## Download a blob
  145. To download a blob, call the **BlobRestProxy->getBlob** method, then call the **getContentStream** method on the resulting **GetBlobResult** object.
  146. require_once 'vendor/autoload.php';
  147. use WindowsAzure\Common\ServicesBuilder;
  148. use MicrosoftAzure\Storage\Common\ServiceException;
  149. // Create blob REST proxy.
  150. $blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);
  151. try {
  152. // Get blob.
  153. $blob = $blobRestProxy->getBlob("mycontainer", "myblob");
  154. fpassthru($blob->getContentStream());
  155. }
  156. catch(ServiceException $e){
  157. // Handle exception based on error codes and messages.
  158. // Error codes and messages are here:
  159. // http://msdn.microsoft.com/library/azure/dd179439.aspx
  160. $code = $e->getCode();
  161. $error_message = $e->getMessage();
  162. echo $code.": ".$error_message."<br />";
  163. }
  164. Note that the example above gets a blob as a stream resource (the default behavior). However, you can use the [stream\_get\_contents][stream-get-contents] function to convert the returned stream to a string.
  165. ## Delete a blob
  166. To delete a blob, pass the container name and blob name to **BlobRestProxy->deleteBlob**.
  167. require_once 'vendor/autoload.php';
  168. use WindowsAzure\Common\ServicesBuilder;
  169. use MicrosoftAzure\Storage\Common\ServiceException;
  170. // Create blob REST proxy.
  171. $blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);
  172. try {
  173. // Delete blob.
  174. $blobRestProxy->deleteBlob("mycontainer", "myblob");
  175. }
  176. catch(ServiceException $e){
  177. // Handle exception based on error codes and messages.
  178. // Error codes and messages are here:
  179. // http://msdn.microsoft.com/library/azure/dd179439.aspx
  180. $code = $e->getCode();
  181. $error_message = $e->getMessage();
  182. echo $code.": ".$error_message."<br />";
  183. }
  184. ## Delete a blob container
  185. Finally, to delete a blob container, pass the container name to **BlobRestProxy->deleteContainer**.
  186. require_once 'vendor/autoload.php';
  187. use WindowsAzure\Common\ServicesBuilder;
  188. use MicrosoftAzure\Storage\Common\ServiceException;
  189. // Create blob REST proxy.
  190. $blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);
  191. try {
  192. // Delete container.
  193. $blobRestProxy->deleteContainer("mycontainer");
  194. }
  195. catch(ServiceException $e){
  196. // Handle exception based on error codes and messages.
  197. // Error codes and messages are here:
  198. // http://msdn.microsoft.com/library/azure/dd179439.aspx
  199. $code = $e->getCode();
  200. $error_message = $e->getMessage();
  201. echo $code.": ".$error_message."<br />";
  202. }
  203. ## Next steps
  204. Now that you've learned the basics of the Azure blob service, follow these links to learn about more complex storage tasks.
  205. - Visit the [Azure Storage team blog](http://blogs.msdn.com/b/windowsazurestorage/)
  206. - See the [PHP block blob example](https://github.com/WindowsAzure/azure-sdk-for-php-samples/blob/master/storage/BlockBlobExample.php).
  207. - See the [PHP page blob example](https://github.com/WindowsAzure/azure-sdk-for-php-samples/blob/master/storage/PageBlobExample.php).
  208. - [Transfer data with the AzCopy Command-Line Utility](storage-use-azcopy.md)
  209. For more information, see also the [PHP Developer Center](/develop/php/).
  210. [download]: http://go.microsoft.com/fwlink/?LinkID=252473
  211. [container-acl]: http://msdn.microsoft.com/library/azure/dd179391.aspx
  212. [error-codes]: http://msdn.microsoft.com/library/azure/dd179439.aspx
  213. [file_get_contents]: http://php.net/file_get_contents
  214. [require_once]: http://php.net/require_once
  215. [fopen]: http://www.php.net/fopen
  216. [stream-get-contents]: http://www.php.net/stream_get_contents