Access Azure Blob Storage with PHP

PHP:7.2

Azure 本身有提供 azure-storage-php 這個 PHP Client Libraries 讓使用 PHP 的開發者可以操作 Azure Blob Storage

azure-storage-php 裡面又細分成數個 repo,可以根據需要的操作功能做選擇,這篇就先以 azure-storage-blob: 1.5.2 當範例。

Installation

透過 composer 便可以安裝使用。

composer require microsoft/azure-storage-blob

Configuration

操作 Azure Blob Storage 需要兩種資訊,一個是 Storage AccountConnection String,另一個則是 Container Name

Connection String,可以從 Storage Account 介面左邊的 存取金鑰(Access Keys) 看到。

require_once "vendor/autoload.php";

use MicrosoftAzure\Storage\Blob\BlobRestProxy;

$connectionString = 'DefaultEndpointsProtocol=https;AccountName=XXXXXX;AccountKey=XXXXXX;EndpointSuffix=core.windows.net';

$blobClient = BlobRestProxy::createBlobService($connectionString);

// Container Name
$myContainer = 'XXXXXXX';

Basic Usage

上傳檔案

use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;

$content = fopen('4710765081331-1.xml', 'r');
// Virtual Hierarchy
$blobName = 'company/4710765081331-1.xml';

try {
    // Upload blob
    $blobClient->createBlockBlob($myContainer, $blobName, $content);
} catch (ServiceException $e) {
    $code = $e->getCode();
    $errorMessage = $e->getMessage();
    echo $code . ': ' . $errorMessage . PHP_EOL;
}

下載檔案

use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;

try {
    // Download blob
    $getBlobResult = $blobClient->getBlob($myContainer, 'xx.png');
} catch (ServiceException $e) {
    $code = $e->getCode();
    $errorMessage = $e->getMessage();
    echo $code . ': ' . $errorMessage . PHP_EOL;
}

file_put_contents("xx.png", $getBlobResult->getContentStream());

建立 Container

use MicrosoftAzure\Storage\Blob\Models\CreateContainerOptions;
use MicrosoftAzure\Storage\Blob\Models\PublicAccessType;
use MicrosoftAzure\Storage\Common\Exceptions\ServiceException;

$createContainerOptions = new CreateContainerOptions();

// 設定 Public Access 權限
$createContainerOptions->setPublicAccess(PublicAccessType::CONTAINER_AND_BLOBS);

// 設定 Metadata
$createContainerOptions->addMetaData("key1", "value1");

try {
    // Create Container
    $blobClient->createContainer($myContainer, $createContainerOptions);
} catch (ServiceException $e) {
    $code = $e->getCode();
    $errorMessage = $e->getMessage();
    echo $code . ': ' . $errorMessage . PHP_EOL;
}

取得 Container Property

$properties = $blobClient->getContainerProperties($myContainer);
echo 'Last modified: ' . $properties->getLastModified()->format('Y-m-d H:i:s') . PHP_EOL;
echo 'ETAG: ' . $properties->getETag() . PHP_EOL;