使用 PHP 在 Azure Blob 儲存體之間傳送物件Transfer objects to/from Azure Blob storage using PHP

在本快速入門中,您會了解如何使用 PHP 在 Azure Blob 儲存體容器中上傳、下載及列出區塊 Blob。In this quickstart, you learn how to use PHP to upload, download, and list block blobs in a container in Azure Blob storage.

先決條件Prerequisites

若要存取 Azure 儲存體,您需要有 Azure 訂用帳戶。To access Azure Storage, you'll need an Azure subscription. 如果您還沒有訂用帳戶,請先建立免費帳戶,再開始操作。If you don't already have a subscription, create a free account before you begin.

對 Azure 儲存體的所有存取都是透過儲存體帳戶進行。All access to Azure Storage takes place through a storage account. 在本快速入門中,使用 Azure 入口網站、Azure PowerShell 或 Azure CLI 建立儲存體帳戶。For this quickstart, create a storage account using the Azure portal, Azure PowerShell, or Azure CLI. 如需建立儲存體帳戶的協助,請參閱建立儲存體帳戶For help creating a storage account, see Create a storage account.

請確定您已安裝下列額外的必要條件:Make sure you have the following additional prerequisites installed:

下載範例應用程式Download the sample application

本快速入門中使用的範例應用程式是基本的 PHP 應用程式。The sample application used in this quickstart is a basic PHP application.

使用 git 將應用程式的複本下載至您的開發環境。Use git to download a copy of the application to your development environment.

git clone https://github.com/Azure-Samples/storage-blobs-php-quickstart.git

此命令會將存放庫複製到本機的 git 資料夾。This command clones the repository to your local git folder. 若要開啟 PHP 範例應用程式,請尋找 storage-blobs-php-quickstart 資料夾,然後開啟 phpqs.php 檔案。To open the PHP sample application, look for the storage-blobs-php-quickstart folder, and open the phpqs.php file.

從 Azure 入口網站複製您的認證Copy your credentials from the Azure portal

範例應用程式必須授與對您儲存體帳戶的存取權。The sample application needs to authorize access to your storage account. 請以連接字串的形式將您的儲存體帳戶認證提供給應用程式。Provide your storage account credentials to the application in the form of a connection string. 若要檢視您的儲存體帳戶認證:To view your storage account credentials:

  1. Azure 入口網站中,移至您的儲存體帳戶。In to the Azure portal go to your storage account.

  2. 在儲存體帳戶概觀的 [設定] 區段中,選取 [存取金鑰] 以顯示您的帳戶存取金鑰和連接字串。In the Settings section of the storage account overview, select Access keys to display your account access keys and connection string.

  3. 請記下您的儲存體帳戶名稱,您在驗證時將需用到。Note the name of your storage account, which you'll need for authorization.

  4. 尋找 [金鑰 1] 下方的 [金鑰] 值,然後選取 [複製] 以複製帳戶金鑰。Find the Key value under key1, and select Copy to copy the account key.

    顯示如何從 Azure 入口網站複製帳戶金鑰的螢幕擷取畫面

設定儲存體連接字串Configure your storage connection string

在應用程式中,您必須提供儲存體帳戶名稱和帳戶金鑰,才能建立應用程式的 BlobRestProxy 執行個體。In the application, you must provide your storage account name and account key to create the BlobRestProxy instance for your application. 建議您在執行應用程式的本機電腦上,將這些識別碼儲存在環境變數內。It is recommended to store these identifiers within an environment variable on the local machine running the application. 請根據您的作業系統,使用以下其中一個範例來建立環境變數。Use one of the following examples depending on your Operating System to create the environment variable. 使用您的帳戶名稱和金鑰取代 youraccountnameyouraccountkey 值。Replace the youraccountname and youraccountkey values with your account name and key.

export ACCOUNT_NAME=<youraccountname>
export ACCOUNT_KEY=<youraccountkey>

設定環境Configure your environment

從本機 git 資料夾取得資料夾,並將它放在您的 PHP 伺服器所提供的目錄中。Take the folder from your local git folder and place it in a directory served by your PHP server. 然後,開啟範圍限於該相同目錄的命令提示字元並輸入:php composer.phar installThen, open a command prompt scoped to that same directory and enter: php composer.phar install

執行範例Run the sample

這個範例會在 '.' 資料夾中建立測試檔案。This sample creates a test file in the '.' folder. 範例程式會將測試檔案上傳至 Blob 儲存體、列出容器中的 Blob,並下載具有新名稱的檔案。The sample program uploads the test file to Blob storage, lists the blobs in the container, and downloads the file with a new name.

執行範例。Run the sample. 下列輸出是執行應用程式時所傳回的輸出範例:The following output is an example of the output returned when running the application:

Uploading BlockBlob: HelloWorld.txt
These are the blobs present in the container: HelloWorld.txt: https://myexamplesacct.blob.core.windows.net/blockblobsleqvxd/HelloWorld.txt

This is the content of the blob uploaded: Hello Azure!

當您按所顯示的按鈕時,範例程式會刪除儲存體容器和檔案。When you press the button displayed, the sample program deletes the storage container and the files. 在繼續之前,請檢查您伺服器的資料夾,找出這兩個檔案。Before you continue, check your server's folder for the two files. 您可以開啟它們,並查看它們是否相同。You can open them and see they are identical.

您也可以使用 Azure 儲存體總管 之類的工具來檢視 Blob 儲存體中的檔案。You can also use a tool such as the Azure Storage Explorer to view the files in Blob storage. Azure 儲存體總管是免費的跨平台工具,可讓您存取儲存體帳戶資訊。Azure Storage Explorer is a free cross-platform tool that allows you to access your storage account information.

確認檔案之後,請按任一鍵以完成示範並刪除測試檔案。After you've verified the files, hit any key to finish the demo and delete the test files. 現在您已知道這個範例的功用,請開啟 example.rb 檔案查看程式碼。Now that you know what the sample does, open the example.rb file to look at the code.

了解範例程式碼Understand the sample code

接下來,我們將透過範例程式碼來了解其運作方式。Next, we walk through the sample code so that you can understand how it works.

取得儲存體物件的參考Get references to the storage objects

第一件事是建立用來存取和管理 Blob 儲存體的物件參考。The first thing to do is create the references to the objects used to access and manage Blob storage. 這些物件是互為建置基礎,各自都為清單中的下一個物件所使用。These objects build on each other, and each is used by the next one in the list.

  • 建立 Azure 儲存體 BlobRestProxy 物件的執行個體來設定連線認證。Create an instance of the Azure storage BlobRestProxy object to set up connection credentials.
  • 建立 BlobService 物件,它會指向儲存體帳戶中的 Blob 服務。Create the BlobService object that points to the Blob service in your storage account.
  • 建立 Container 物件,它代表您要存取的容器。Create the Container object, which represents the container you are accessing. 容器是用來組織 Blob,就像在電腦上用資料夾組織檔案一樣。Containers are used to organize your blobs like you use folders on your computer to organize your files.

一旦有了 blobClient 容器物件,您就可以建立 Block Blob 物件,以指向您感興趣的特定 Blob。Once you have the blobClient container object, you can create the Block blob object that points to the specific blob in which you are interested. 您可接著執行上傳、下載和複製等作業。Then you can perform operations such as upload, download, and copy.

重要

容器名稱必須是小寫字母。Container names must be lowercase. 如需有關容器和 Blob 名稱的詳細資訊,請參閱命名和參考容器、Blob 及中繼資料See Naming and Referencing Containers, Blobs, and Metadata for more information about container and blob names.

在本節中,您可以設定 Azure 儲存體用戶端的執行個體、具現化 blob 服務物件、建立新的容器,以及設定容器上的權限,以便這些 Blob 為公用 Blob。In this section, you set up an instance of Azure storage client, instantiate the blob service object, create a new container, and set permissions on the container so the blobs are public. 容器名為 quickstartblobsThe container is called quickstartblobs.

    # Setup a specific instance of an Azure::Storage::Client
    $connectionString = "DefaultEndpointsProtocol=https;AccountName=".getenv('account_name').";AccountKey=".getenv('account_key');
    
    // Create blob client.
    $blobClient = BlobRestProxy::createBlobService($connectionString);
    
    # Create the BlobService that represents the Blob service for the storage account
    $createContainerOptions = new CreateContainerOptions();
    
    $createContainerOptions->setPublicAccess(PublicAccessType::CONTAINER_AND_BLOBS);
    
    // Set container metadata.
    $createContainerOptions->addMetaData("key1", "value1");
    $createContainerOptions->addMetaData("key2", "value2");

    $containerName = "blockblobs".generateRandomString();

    try    {
        // Create container.
        $blobClient->createContainer($containerName, $createContainerOptions);

將 Blob 上傳到容器Upload blobs to the container

Blob 儲存體支援區塊 Blob、附加 Blob 和分頁 Blob。Blob storage supports block blobs, append blobs, and page blobs. 最常使用的是區塊 Blob,這也是本快速入門中所使用的。Block blobs are the most commonly used, and that is what is used in this quickstart.

若要將檔案上傳至 Blob,請加入本機磁碟機上的目錄名稱和檔案名稱,取得檔案的完整路徑。To upload a file to a blob, get the full path of the file by joining the directory name and the file name on your local drive. 然後,您可以使用 createBlockBlob() 方法,將檔案上傳至指定的路徑。You can then upload the file to the specified path using the createBlockBlob() method.

範例程式碼會取得本機檔案並將它上傳至 Azure。The sample code takes a local file and uploads it to Azure. 此檔案會在程式碼中儲存為 myfile,而 Blob 的名稱會儲存為 fileToUploadThe file is stored as myfile and the name of the blob as fileToUpload in the code. 下列範例會將檔案上傳到名為 quickstartblobs 的容器。The following example uploads the file to your container called quickstartblobs.

    $myfile = fopen("HelloWorld.txt", "w") or die("Unable to open file!");
    fclose($myfile);

    # Upload file as a block blob
    echo "Uploading BlockBlob: ".PHP_EOL;
    echo $fileToUpload;
    echo "<br />";
    
    $content = fopen($fileToUpload, "r");

    //Upload blob
    $blobClient->createBlockBlob($containerName, $fileToUpload, $content);

若要執行區塊 blob 的部分更新內容,請使用 createblocklist() 方法。To perform a partial update of the content of a block blob, use the createblocklist() method. 區塊 Blob 可以大到 4.7 TB,而且可以是 Excel 試算表到大型視訊檔案的任何一種。Block blobs can be as large as 4.7 TB, and can be anything from Excel spreadsheets to large video files. 分頁 Blob 主要用於備份 IaaS VM 所用的 VHD 檔案。Page blobs are primarily used for the VHD files used to back IaaS VMs. 附加 Blob 用於記錄,例如當您想要寫入檔案,並繼續新增更多資訊時。Append blobs are used for logging, such as when you want to write to a file and then keep adding more information. 附加 blob 應該用於單一寫入模式。Append blob should be used in a single writer model. 儲存在 Blob 儲存體中的大部分物件都是區塊 Blob。Most objects stored in Blob storage are block blobs.

列出容器中的 BlobList the blobs in a container

您可以使用 listBlobs() 方法,取得容器中的檔案清單。You can get a list of files in the container using the listBlobs() method. 下列程式碼會擷取 Blob 的清單,然後透過它們執行迴圈,顯示在容器中找到的 Blob 名稱。The following code retrieves the list of blobs, then loops through them, showing the names of the blobs found in a container.

    $listBlobsOptions = new ListBlobsOptions();
    $listBlobsOptions->setPrefix("HelloWorld");
    
    echo "These are the blobs present in the container: ";
    
    do{
        $result = $blobClient->listBlobs($containerName, $listBlobsOptions);
        foreach ($result->getBlobs() as $blob)
        {
            echo $blob->getName().": ".$blob->getUrl()."<br />";
        }
        
        $listBlobsOptions->setContinuationToken($result->getContinuationToken());
    } while($result->getContinuationToken());

取得 Blob 的內容Get the content of your blobs

使用 getBlob() 方法來取得 blob 的內容。Get the contents of your blobs using the getBlob() method. 下列程式碼會顯示前一節中上傳的 Blob 內容。The following code displays the contents of the blob uploaded in a previous section.

    $blob = $blobClient->getBlob($containerName, $fileToUpload);
    fpassthru($blob->getContentStream());

清除資源Clean up resources

如果不再需要本快速入門中上傳的 Blob,可以使用 deleteContainer() 刪除整個容器。If you no longer need the blobs uploaded in this quickstart, you can delete the entire container using the deleteContainer() method. 如果不再需要建立的檔案,請使用 deleteBlob() 方法來刪除檔案。If the files created are no longer needed, you use the deleteBlob() method to delete the files.

    // Delete blob.
    echo "Deleting Blob".PHP_EOL;
    echo $fileToUpload;
    echo "<br />";
    $blobClient->deleteBlob($_GET["containerName"], $fileToUpload);

    // Delete container.
    echo "Deleting Container".PHP_EOL;
    echo $_GET["containerName"].PHP_EOL;
    echo "<br />";
    $blobClient->deleteContainer($_GET["containerName"]);

    //Deleting local file
    echo "Deleting file".PHP_EOL;
    echo "<br />";
    unlink($fileToUpload);   

可供使用 Blob 開發 PHP 應用程式的資源Resources for developing PHP applications with blobs

請參閱以下可供使用 Blob 儲存體進行 PHP 開發的額外資源:See these additional resources for PHP development with Blob storage:

後續步驟Next steps

在此快速入門中,您已了解如何使用 PHP 在本機磁碟和 Azure Blob 儲存體之間傳輸檔案。In this quickstart, you learned how to transfer files between a local disk and Azure blob storage using PHP. 若要深入了解 PHP 的用法,請繼續使用我們的 PHP 開發人員中心。To learn more about working with PHP, continue to our PHP Developer center.

如需儲存體總管和 Blob 的詳細資訊,請參閱使用儲存體總管管理 Azure Blob 儲存體資源For more information about the Storage Explorer and Blobs, see Manage Azure Blob storage resources with Storage Explorer.