Free trial *Internet Service Required

How to use the Blob service from PHP

This guide will show you how to perform common scenarios using the Windows Azure Blob service. The samples are written in PHP and use the Windows Azure SDK for PHP. The scenarios covered include uploading, listing, downloading, and deleting blobs. For more information on blobs, see the Next Steps section.

Table of Contents

What is Blob Storage

Windows Azure Blob storage is a service for storing large amounts of unstructured data that can be accessed from anywhere in the world via HTTP or HTTPS. A single blob can be hundreds of gigabytes in size, and a single storage account can contain up to 100TB of blobs. Common uses of Blob storage include:

  • Serving images or documents directly to a browser
  • Storing files for distributed access
  • Streaming video and audio
  • Performing secure backup and disaster recovery
  • Storing data for analysis by an on-premises or Windows Azure-hosted service

You can use Blob storage to expose data publicly to the world or privately for internal application storage.

Concepts

The Blob service contains the following components:

Blob1

  • Storage Account: All access to Windows Azure Storage is done through a storage account. This is the highest level of the namespace for accessing blobs. An account can contain an unlimited number of containers, as long as their total size is under 100TB.

  • Container: A container provides a grouping of a set of blobs. All blobs must be in a container. An account can contain an unlimited number of containers. A container can store an unlimited number of blobs.

  • Blob: A file of any type and size. There are two types of blobs that can be stored in Windows Azure Storage: block and page blobs. Most files are block blobs. A single block blob can be up to 200GB in size. This tutorial uses block blobs. Page blobs, another blob type, can be up to 1TB in size, and are more efficient when ranges of bytes in a file are modified frequently. For more information about blobs, see Understanding Block Blobs and Page Blobs.

  • URL format: Blobs are addressable using the following URL format:
    http://<storage account>.blob.core.windows.net/<container>/<blob>

    The following URL could be used to address one of the blobs in the diagram above:
    http://sally.blob.core.windows.net/movies/MOV1.AVI

Create a Windows Azure storage account

To use storage operations, you need a Windows Azure storage account. Youcan create a storage account by following these steps. (You can also create a storage account using the REST API.)

  1. Log into the Windows Azure Management Portal.

  2. At the bottom of the navigation pane, click NEW.

    +new

  3. Click DATA SERVICES, then STORAGE, and then click QUICK CREATE.

    Quick create dialog

  4. In URL, type a subdomain name to use in the URI for the storage account. The entry can contain from 3-24 lowercase letters and numbers. This value becomes the host name within the URI that is used to address Blob, Queue, or Table resources for the subscription.

  5. Choose a Region/Affinity Group in which to locate the storage. If you will be using storage from your Windows Azure application, select the same region where you will deploy your application.

  6. Optionally, you can enable geo-replication.

  7. Click CREATE STORAGE ACCOUNT.

Create a PHP application

The only requirement for creating a PHP application that accesses the Windows Azure Blob service is the referencing of classes in the Windows Azure SDK for PHP from within your code. You can use any development tools to create your application, including Notepad.

In this guide, you will use service features which can be called within a PHP application locally, or in code running within a Windows Azure web role, worker role, or web site.

Get the Windows Azure Client Libraries

Install via Composer

  1. Install Git.

    Note

    On Windows, you will also need to add the Git executable to your PATH environment variable.

  2. Create a file named composer.json in the root of your project and add the following code to it:

    {
        "require": {
            "microsoft/windowsazure": "*"
        },          
        "repositories": [
            {
                "type": "pear",
                "url": "http://pear.php.net"
            }
        ],
        "minimum-stability": "dev"
    }
  3. Download composer.phar in your project root.

  4. Open a command prompt and execute this in your project root

    php composer.phar install

Install manually

To download and install the PHP Client Libraries for Windows Azure manually, follow these steps:

  1. Download a .zip archive that contains the libraries from GitHub. Alternatively, fork the repository and clone it to your local machine. (The latter option requires a GitHub account and having Git installed locally.)

    Note

    The PHP Client Libraries for Windows Azure have a dependency on the HTTP_Request2, Mail_mime, and Mail_mimeDecode PEAR packages. The recommended way to resolve these dependencies is to install these packages using the PEAR package manager.

  2. Copy the WindowsAzure directory of the downloaded archive to your application directory structure.

For more information about installing the PHP Client Libraries for Windows Azure (including information about installing as a PEAR package), see Download the Windows Azure SDK for PHP.

Configure your application to access the Blob service

To use the Windows Azure Blob service APIs, you need to:

  1. Reference the autoloader file using the require_once statement, and
  2. Reference any classes you might use.

The following example shows how to include the autoloader file and reference the ServicesBuilder class.

Note

This example (and other examples in this article) assume you have installed the PHP Client Libraries for Windows Azure via Composer. If you installed the libraries manually or as a PEAR package, you will need to reference the WindowsAzure.php autoloader file.

require_once 'vendor\autoload.php';
use WindowsAzure\Common\ServicesBuilder;

In the examples below, the require_once statement will be shown always, but only the classes necessary for the example to execute will be referenced.

Setup a Windows Azure storage connection

To instantiate a Windows Azure Blob service client you must first have a valid connection string. The format for the blob service connection string is:

For accessing a live service:

DefaultEndpointsProtocol=[http|https];AccountName=[yourAccount];AccountKey=[yourKey]

For accessing the emulator storage:

UseDevelopmentStorage=true

To create any Windows Azure service client you need to use the ServicesBuilder class. You can:

  • pass the connection string directly to it or
  • use the CloudConfigurationManager (CCM)to check multiple external sources for the connection string:
    • by default it comes with support for one external source - environmental variables
    • you can add new sources by extending the ConnectionStringSource class

For the examples outlined here, the connection string will be passed directly.

require_once 'vendor\autoload.php';

use WindowsAzure\Common\ServicesBuilder;

$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);

How to: Create a container

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 ACL and container metadata.)

require_once 'vendor\autoload.php';

use WindowsAzure\Common\ServicesBuilder;
use WindowsAzure\Blob\Models\CreateContainerOptions;
use WindowsAzure\Blob\Models\PublicAccessType;
use WindowsAzure\Common\ServiceException;

// Create blob REST proxy.
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);


// OPTIONAL: Set public access policy and metadata.
// Create container options object.
$createContainerOptions = new CreateContainerOptions(); 

// Set public access policy. Possible values are 
// PublicAccessType::CONTAINER_AND_BLOBS and PublicAccessType::BLOBS_ONLY.
// CONTAINER_AND_BLOBS:     
// Specifies full public read access for container and blob data.
// proxys can enumerate blobs within the container via anonymous 
// request, but cannot enumerate containers within the storage account.
//
// BLOBS_ONLY:
// Specifies public read access for blobs. Blob data within this 
// container can be read via anonymous request, but container data is not 
// available. proxys cannot enumerate blobs within the container via 
// anonymous request.
// If this value is not specified in the request, container data is 
// private to the account owner.
$createContainerOptions->setPublicAccess(PublicAccessType::CONTAINER_AND_BLOBS);

// Set container metadata
$createContainerOptions->addMetaData("key1", "value1");
$createContainerOptions->addMetaData("key2", "value2");

try {
    // Create container.
    $blobRestProxy->createContainer("mycontainer", $createContainerOptions);
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here: 
    // http://msdn.microsoft.com/en-us/library/windowsazure/dd179439.aspx
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

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).

For more information about Blob service error codes, see Blob Service Error Codes.

How to: Upload a Blob into a container

To upload a file as a blob, use the BlobRestProxy->createBlockBlob method. This operation will create the blob if it doesn’t exist, or overwrite it if it does. The code example below assumes that the container has already been created and uses fopen to open the file as a stream.

require_once 'vendor\autoload.php';

use WindowsAzure\Common\ServicesBuilder;
use WindowsAzure\Common\ServiceException;

// Create blob REST proxy.
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);


$content = fopen("c:\myfile.txt", "r");
$blob_name = "myblob";

try {
    //Upload blob
    $blobRestProxy->createBlockBlob("mycontainer", $blob_name, $content);
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here: 
    // http://msdn.microsoft.com/en-us/library/windowsazure/dd179439.aspx
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

Note that the example above uploads a blob as a stream. However, a blob can also be uploaded as a string using, for example, the file_get_contents function. To do this, change $content = fopen("c:\myfile.txt", "r"); in the example above to $content = file_get_contents("c:\myfile.txt");.

How to: List the Blobs in a container

To list the blobs in a container, use the BlobRestProxy->listBlobs method with a foreach loop to loop through the result. The following code outputs the name of each blob in a container and its URI to the browser.

require_once 'vendor\autoload.php';

use WindowsAzure\Common\ServicesBuilder;
use WindowsAzure\Common\ServiceException;

// Create blob REST proxy.
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);


try {
    // List blobs.
    $blob_list = $blobRestProxy->listBlobs("mycontainer");
    $blobs = $blob_list->getBlobs();

    foreach($blobs as $blob)
    {
        echo $blob->getName().": ".$blob->getUrl()."<br />";
    }
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here: 
    // http://msdn.microsoft.com/en-us/library/windowsazure/dd179439.aspx
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

How to: download a Blob

To download a blob, call the BlobRestProxy->getBlob method, then call the getContentStream method on the resulting GetBlobResult object.

require_once 'vendor\autoload.php';

use WindowsAzure\Common\ServicesBuilder;
use WindowsAzure\Common\ServiceException;

// Create blob REST proxy.
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);


try {
    // Get blob.
    $blob = $blobRestProxy->getBlob("mycontainer", "myblob");
    fpassthru($blob->getContentStream());
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here: 
    // http://msdn.microsoft.com/en-us/library/windowsazure/dd179439.aspx
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

Note that the example above gets a blob as a stream resource (the default behavior). However, you can use the stream_get_contents function to convert the returned stream to a string.

How to: Delete a Blob

To delete a blob, pass the container name and blob name to BlobRestProxy->deleteBlob.

require_once 'vendor\autoload.php';

use WindowsAzure\Common\ServicesBuilder;
use WindowsAzure\Common\ServiceException;

// Create blob REST proxy.
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);


try {
    // Delete container.
    $blobRestProxy->deleteBlob("mycontainer", "myblob");
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here: 
    // http://msdn.microsoft.com/en-us/library/windowsazure/dd179439.aspx
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

How to: Delete a Blob container

Finally, to delete a blob container, pass the container name to BlobRestProxy->deleteContainer.

require_once 'vendor\autoload.php';

use WindowsAzure\Common\ServicesBuilder;
use WindowsAzure\Common\ServiceException;

// Create blob REST proxy.
$blobRestProxy = ServicesBuilder::getInstance()->createBlobService($connectionString);


try {
    // Delete container.
    $blobRestProxy->deleteContainer("mycontainer");
}
catch(ServiceException $e){
    // Handle exception based on error codes and messages.
    // Error codes and messages are here: 
    // http://msdn.microsoft.com/en-us/library/windowsazure/dd179439.aspx
    $code = $e->getCode();
    $error_message = $e->getMessage();
    echo $code.": ".$error_message."<br />";
}

Next steps

Now that you’ve learned the basics of the Windows Azure Blob service, follow these links to learn how to do more complex storage tasks.

Rss Newsletter