5 12 2009
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:
- Windows Azure CTP account registered and blob storage account configured (or you have Windows Azure SDK + all necessary development tools installed to your development machine and configured),
- Apache or IIS web server with PHP support,
- Windows Azure SDK for PHP downloaded and unpacked.
If you need more information then please check out these resources:
- you can find SDK documentation from downloaded packaged (there is folder called documentation),
- PHP on Windows Training Kit (August 2009),
- Windows Azure Platform Training Kit – November Update.
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.
// Connect to Windows Azure cloud storage
$client = new Microsoft_WindowsAzure_Storage_Blob(
// 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.
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.