Using Windows Azure BLOB storage with PHP

My last posting described how to read and write files located in Windows Azure cloud storage. In this posting I will show you how to do almost same thing using PHP. We will use Windows Azure SDK for PHP. The purpose of this example is to show you how simple it is to use Windows Azure storage services in your PHP applications.

Preparing for example

I expect you have everything needed for this example:

If you need more information then please check out these resources:

Before we start scripting let’s make sure that our environment is configured correctly:

  • copy folder named Microsoft to your script folder (or somewhere else where PHP file include functions can access it),
  • let PHP display errors to page if you don’t prefer to read log files,
  • make sure you have cURL extension enabled in php.ini file.

Reading and writing cloud storage files

Our script does two simple operations – it reads one file from Windows Azure BLOB storage and writes the other one there.  Note that in the beginning of script I turn on error reporting and set content type as plain text. If there are any errors or warnings then this information is written out and formatted so it is easy to read.

<?php 
error_reporting(E_ALL); 
header(‘Content-type: text/plain’); 
require_once ‘Microsoft/WindowsAzure/Storage/Blob.php’; 

// Connect to Windows Azure cloud storage 
$client = new Microsoft_WindowsAzure_Storage_Blob(
 
                    
"blob.core.windows.net",
 
                    
"<ACCOUNT>",
 
                    
"<KEY>"
 
                    
); 

// Read file Data.xml from container called dataset 
$localpath = getcwd() . ‘\Data.xml’; 
$client->getBlob(‘dataset’, ‘Data.xml’, $localpath); 

// Write file example.txt to container called dataset 
$localpath = getcwd() . ‘\example.txt’; 
$result = $client->putBlob(‘dataset’, ‘example.txt’, $localpath); 
?>

Some notes too. Windows Azure SDK for PHP handles cloud storage address as raw host name. <ACCOUNT> – you cloud storage service name – is used with raw host name to build up correct cloud storage URL. It is handled by library and you don’t have to worry about it. <KEY> is base64 encoded key and it is generated when you create your BLOB storage service.

Conclusion

It is very easy to communicate with Windows Azure cloud storage services using PHP and Windows Azure SDK for PHP. The code example above shows also one good thing: we wrote very basic and extremely simple code to get our works done – even complete beginners are able to use Windows Azure cloud storage in their scripts.

Gunnar Peipman

Gunnar Peipman is ASP.NET, Azure and SharePoint fan, Estonian Microsoft user group leader, blogger, conference speaker, teacher, and tech maniac. Since 2008 he is Microsoft MVP specialized on ASP.NET.

    Leave a Reply

    Your email address will not be published. Required fields are marked *