Host PHP in the Cloud with Windows Azure

More than a buzzword in executive meetings, cloud computing is the next big thing in the world of IT. Clouds offer an infinite amount of resources, both on demand and in pay-per-use models: computer resources on tap! In this article, I’ll focus on one of these cloud platforms, Microsoft’s Windows Azure, and give you all the information you need to get started developing PHP applications on this platform. Although we won’t go too deep into the technicalities, I will point you to further information and resources on specific points as we go.

By the time you’re done, you should have a good understanding of the Windows Azure Platform, and you can test your knowledge in our Article Quiz.

Different Clouds

Choice is a good thing. The great news for us developers is that there are many choices when it comes to cloud computing. Microsoft, Google, Amazon, Rackspace, GoGrid, and many others offer cloud products that have their own special characteristics. It looks like the whole world is dividing these offers into two distinct categories: IaaS (Infrastructure-as-a-Service) and PaaS (Platform-as-a-Service)—the difference between the two is illustrated in Figure 1, “The difference between cloud platforms”.

Figure 1. The difference between cloud platforms

The difference between cloud platforms


First, let’s look at IaaS. Amazon EC2 was the first to offer virtual machines that could run your application. These virtual machines, however, are under your control, like physical servers in your data center. This means that you’re in control of patches, security, maintenance to the operating system—and all with full root or administrator access. The cloud platform takes the infrastructure woes out of your hands, as networking, load balancers, and firewalls are handled for you.

Next, there’s PaaS. This approach is also based on virtual machines, but you don’t have control over them. Instead, a set of tools and APIs is provided to let you package your application and upload it onto your virtual machine, so the only thing you have to worry about is your application. The networking, operating system, and so on are all maintained by the cloud platform.

All cloud vendors share common features, including virtual machines, and storage that’s available through REST-based protocols. Then again, each offering has its own unique features, which is good: clouds are still in a very innovative phase, and as developers we have the luxury of choosing the platform that’s best suited to our particular applications.

Windows Azure Platform Overview

Throughout this article, I’ll be describing the Windows Azure Platform, Microsoft’s PaaS offering to the world of cloud computing. But before we dive into technical details, let’s get a feel for the components included in this offering, and what they do.

Windows Azure

Windows Azure is the core component of the Windows Azure Platform. The marketing folks describe this component as the “operating system for the Azure cloud.” I’m not a big fan of marketing folks and their quotes, but for once, they’re right! Windows Azure is the heart of Microsoft’s offering, and it does what you’d expect of any operating system: it allows you to run your application on a virtual machine, either in a web role (with a web server installed) or in a worker role—a cleaner virtual machine that allows you to host other types of applications.

Windows Azure also allows you to scale up rapidly: simply change a configuration value and you’ll have multiple instances running a the snap of your fingers. Load balancing is taken care of automatically and requires no configuration.

Next to the operating system, a set of storage services is included, which is accessible through a REST-based API. Blob storage allows you to host any file: text files, images, downloads, and more. Table storage is, in essence, a document database that has limited querying possibilities but can scale massively. And then there are queues, which are mostly used for communications between web and worker roles.

Windows Azure is the location where your application will be hosted. A web role will host your web application; you’ll probably use blob storage to store files, and possibly table storage (or SQL Azure, which we’ll discuss in a moment) to store your data. Windows Azure is also used by other components of the platform.

SQL Azure

In addition to hosting, you will probably need a place where you can store your relational data. This is where SQL Azure comes in: it’s a slightly modified version of Microsoft SQL Server that delivers all the services you’d expect from a database: tables, views, indexes, stored procedures, triggers, and so on.

SQL Azure provides database services in a scalable and reliable way. Data is replicated across different sites and made available through a load balancer, giving you a lot of performance on the data layer of your application.

Windows Azure Platform AppFabric

Windows Azure Platform AppFabric is, in essence, a combination of two products. There’s an Access Control Service to which you can delegate the tasks of authentication and authorization of users, and there’s the Service Bus, which, in my opinion, is one of the features that really makes Windows Azure stand out. In short, the service bus allows you to establish communication between two endpoints. That might be a service that publishes messages to a set of subscribers, but the service bus can also be used for punching holes in firewalls!

Imagine having applications A and B, each in different networks, behind different firewalls. No direct communication seems possible, yet the AppFabric service bus will make sure both applications can communicate. There’s no need to open up ports in your company’s firewall to have your cloud application communicate with an on-premises application.

Live Services

Live Services provides an online identity system that you probably already know: Windows Live ID. Live Services also offers features like presence awareness, search, mapping via Bing Maps, synchronization, and more.

Codename Projects: Dallas and Sydney

These products are still in their incubation phases, and will probably undergo some changes in the future. Nevertheless, they already offer some great features. Dallas is basically a Data-as-a-Service solution through which you can subscribe to various sets of data offered in an open format, OData, which is based on REST and Atom. It also provides your business with a new source of revenue: if you’re sitting on a lot of useful data, why not make it available via Dallas and have others pay for using it?

Project Sydney is different: it’s focused on how you communicate with your cloud application. Currently, that communication is completed through the public Internet, but Sydney will allow you to set up a VPN connection to your virtual machines, enabling you to secure communications using your own security certificates and such.

Tools and APIs Available for PHP

When we’re talking about using PHP in a cloud platform like Windows Azure, there are some objectives that we should fulfil before we start to work with the cloud. You’ll need the right tools to build and deploy your application, but also the right APIs—those that allow you to use the platform and all of its features.

Microsoft has been doing a lot of good work in this area. Yes, Windows Azure is a Windows-based platform that seems to target only .NET languages. However, when you look at the tools, tutorials, APIs, and blog posts around PHP and Windows Azure, it is clear that PHP is an equally valued citizen of the platform!

Let’s take a tour of all the tools and APIs that are available for PHP on Windows Azure today. A lot of these tools are very easy to install using the Web Platform Installer—a “check-next-finish” wizard that allows you to install platforms and tools in an easy and efficient manner.

IDE Support

Of course, you can use your favorite editor to work on a PHP application that’ll be hosted on Windows Azure. On the other hand, if you’re using an Eclipse-based editor like Eclipse PDT, Zend Studio, or Aptana, you can take advantage of a great plugin that will speed up your development efforts, shown in Figure 2, “Using Eclipse for development”. The Eclipse plugin for Windows Azure is available at http://windowsazure4e.org. Also, Josh Holmes has prepared a handy post, Easy Setup for PHP on Azure Development.

Figure 2. Using Eclipse for development

Using Eclipse for development


After installing the plugin, you’ll find the following features have been added to your IDE:

  • Project Creation and Migration allows for the easy migration of an existing application to a Windows Azure application. This tool will get your application ready for packaging and deployment to Windows Azure.

  • Storage Explorer provides access to your Windows Azure storage accounts and allows you to upload and download blobs, query tables, list queues, and so on.

  • Debugging and local testing is also included: there’s no need to deploy and test your application immediately on Windows Azure. A “local cloud” simulation environment is available.

Packaging

Once your application is ready for deployment, it should be packaged for Windows Azure. Packaging is basically the process of creating a ZIP archive of your application and embedding a manifest of all the included files and their configuration requirements.

The Eclipse plugin for Windows Azure contains this feature. However, if you don’t use Eclipse as your IDE, or if you’re working in a non-Windows environment, you can package your application using the Windows Azure command-line tools for PHP developers.

Development Tools and SDKs

Next, let’s take a spin around some of the tools and SDKs that Windows Azure makes available to developers.

Windows Azure SDK for PHP

If you’re planning on migrating an application or building a new one for Windows Azure, chances are that you’ll need storage. This is where the Windows Azure SDK for PHP comes in handy: it gives you easy access to the blob storage, table storage and queue services provided by Windows Azure. You can download this SDK as a stand-alone, open-source package that allows you to access storage from both on-premises locations and your cloud application. If you’re using the Eclipse plug-in we discussed earlier, you’ll find this API is included.

The process of utilizing storage always starts with setting up your credentials: an account name and a shared key (think of this as a very long password). Then, you can use one of the specific classes available for blob storage, table storage, or queue storage.

Here’s an example of blob storage in action. First, I create a container (think of this as a virtual hard drive). Then, I upload a file from my local hard drive to blob storage:

/** Microsoft_WindowsAzure_Storage_Blob */require_once 'Microsoft/WindowsAzure/Storage/Blob.php';$storageClient = new Microsoft_WindowsAzure_Storage_Blob();$storageClient->createContainer('testcontainer');// upload /home/maarten/example.txt to Windows Azure$result = $storageClient->putBlob('testcontainer', 'example.txt', '/home/maarten/example.txt');

Reading the blob afterwards is fairly straightforward:

/** Microsoft_WindowsAzure_Storage_Blob */require_once 'Microsoft/WindowsAzure/Storage/Blob.php';$storageClient = new Microsoft_WindowsAzure_Storage_Blob();// download file to /home/maarten/example.txt$storageClient->getBlob('testcontainer', 'example.txt', '/home/maarten/example.txt');

Table storage is a bit more complex. It’s like a very scalable database that’s not bound to a schema, and has limited querying possibilities. To use table storage, you’ll require some classes that can be used both by your PHP application and Windows Azure table storage. Here’s an example class representing a person:

class Person extends Microsoft_WindowsAzure_Storage_TableEntity{  /**   * @azure Name   */  public $Name;      /**   * @azure Age Edm.Int64   */  public $Age;}

Inserting an instance of Person into the table is as easy as creating a new instance and assigning it some properties. After that, the table storage API in the Windows Azure SDK for PHP allows you to insert the entity into a table named testtable:

/** Microsoft_WindowsAzure_Storage_Table */require_once 'Microsoft/WindowsAzure/Storage/Table.php';$entity = new Person('partition1', 'row1');$entity->Name = "Maarten";$entity->Age = 25;$storageClient = new Microsoft_WindowsAzure_Storage_Table('table.core.windows.net', 'myaccount', 'myauthkey');$storageClient->insertEntity('testtable', $entity);

That was a lot of information in one code snippet! First of all, what are partition1 and row1? Well, those are the partition key and row key. The partition key is a logical grouping of entities. In an application where users can contribute blog posts, for example, a good candidate for the partition key would be the username—this would allow you to easily query for all data related to a given user. The row key is the unique identifier for the row.

Queues follow the same idea—there’s an API that allows you to put, get, and delete messages from the queue on Windows Azure. Queues are also guaranteed to be processed: when a message is read from the queue, data is made invisible for a specific time. If, after that time, the message has not been explicitly removed, for example because a batch script has crashed, the message will re-appear and be available for processing again.

The Windows Azure SDK for PHP also has some extra features that are specific to both PHP and Windows Azure. This includes features like a session storage provider that allows you to share web session data over multiple web role instances. Another feature is a stream wrapper that allows you to use standard file functions like fopen on blob storage.

An example application, ImageCloud, which uses all the features described above, is available for download on my blog.

SQL Server Driver for PHP

The SQL Server Driver for PHP allows PHP developers to access SQL Server databases that are hosted on SQL Server or SQL Azure. The SQL Server Driver for PHP relies on the Microsoft SQL Server ODBC Driver to handle low-level communication with SQL Server. As a result, the SQL Server Driver for PHP is only supported on Windows and Windows Azure. It can be downloaded and installed as a PHP extension.

When you download this driver, be sure to download version 2.0. This version has the additional benefit that it provides PDO (PHP Data Objects) support, which allows you to quickly switch between, for example, MySQL and SQL Server.

Now, let’s imagine you have an SQL Azure database. The following code shows how you can connect to the blog database on your SQL Azure database server and retrieve the posts ordered by publication date:

// Connect to SQL Azure using PDO$connection = new PDO('bvoj6aovnk.database.windows.net', 'sqladm@bvoj6aovnk', 'mypassword', array('Database' => 'blog'));// Fetch specific post$posts = array();$query = 'SELECT * FROM posts ORDER BY PubDate DESC';$statement = $connection->query($query);while ( $row = $statement->fetchObject('Post') ) {  $posts[] = $row;}

AppFabric SDK for PHP

As I mentioned before, the Windows Azure Platform AppFabric (not to be confused with the Windows Server AppFabric) enables you to delegate user authentication and authorization, and to punch firewalls and connect applications across different protected networks with ease. You can download it from http://dotnetservicesphp.codeplex.com.

In terms of authentication and authorization, it’s important to know a little about claims-based authentication and federation—a topic on which some interesting resources are available. Basically, your application establishes a trust relationship with an authentication authority (like Windows Azure Platform AppFabric), which means that your application trusts users that are authenticated with that authority. Next, your application will ask its users to claim their rights. For example, my application could ask the user to claim that they can create orders:

$requiredClaims = array('CreateOrder' => true);if (ValidateClaimUtil::ValidateClaims($requiredClaims, "phpservice", 'http://localhost/SalesDashboard/', $signingKey)){  // User is allowed to create an order!} else{  // User is not authorized.}

The Windows Azure Platform AppFabric Access Control Service will validate that the user has this claim, and sign a security token with that information. Since your application trusts this authority, it will either continue or fail on the basis of whether or not the claim is valid.

Now magine having two applications that cannot connect to each other because of firewall-related policies. If both applications can establish an outgoing connection to the service bus, the service bus will relay communication between the two applications. It’s as easy as that—and incredibly useful if you have a tough IT department!

Figure 3. The benefits of Windows Azure Platform AppFabric Service Bus

The benefits of Windows Azure Platform AppFabric Service Bus


Showing you example code of how this works would lead us too far (since it would involve some configuration and set up tasks). But if you think this sounds like a great feature, check the AppFabric for PHP website, which contains plenty of tutorials on this matter.

Other Features

In addition all the features and APIs we’ve already investigated, there are a number of other features and products that are worth looking at. These features aren’t always Windows Azure-specific, like the URL rewriting module for IIS7, but your application can benefit greatly from them all the same.

PHP Azure Contributions

The Windows Azure platform provides some useful features, like reading configuration files (which can be modified even after a deployment has been done), or logging into the Windows Azure environment and accessing local storage on a virtual machine to store files temporarily. Unfortunately, these features are baked in to the Windows Azure Cloud Guest OS, and not available as REST services. Luckily however, these features are exposed as a C dynamic link library, which means that writing a PHP extension to interface with them is a logical step. And that’s exactly what the PHP Azure Contributions library provides: a PHP extension to make use of configuration data, logging, and local storage. Imagine having a configuration value named EmailSubject in your ServiceConfiguration.csdef file. Reading this value is very easy using the PHP Azure Contributions extension:

$$emailSubject = azure_getconfig("EmailSubject");

We can also write data to the Windows Azure diagnostics log. Here’s an example in which I’m writing an informational message in the diagnostics log:

azure_log("This is some useful information!", "Information");

The PHP Azure Contributions project is available on CodePlex at http://phpazurecontrib.codeplex.com.

URL Rewriting

As a PHP developer, you may already use URL rewriting. In Apache’s .htaccess files, it’s very easy to enable the rewrite engine, and to rewrite incoming URLs to real scripts. For example, the URL http://www.example.com/products/books may be mapped to http://www.example.com/index.php?page=products&category=books on your server. This technique is also available in IIS7, the Microsoft web server that’s also used in Windows Azure web roles. The above URL rewriting example can be defined in the Web.config file in the root of your Windows Azure application:

<?xml version="1.0" encoding="UTF-8"?><configuration>  <system.webServer>    <rewrite>      <rules>        <rule name="RewriteProductsUrl" enabled="true" stopProcessing="true">          <match url="^products/([^/]+)/?$" />          <conditions>            <add input="{REQUEST_FILENAME}" matchType="IsFile" negate="true" />            <add input="{REQUEST_FILENAME}" matchType="IsDirectory" negate="true" />          </conditions>          <action type="Rewrite" url="index.php?page=products&category={R:1}" />        </rule>      </rules>    </rewrite>  </system.webServer></configuration>

Also note that, because your application is hosted on an IIS web server in Windows Azure, you can use any HttpModule for IIS, just as you would for a traditionally hosted application. This makes it easy to enable output compression, leverage the IIS authentication and authorization features, and more. Download the IIS URL Rewrite module from http://www.iis.net/download/urlrewrite.

WinCache Extension

As you may know, PHP files are interpreted into bytecode and executed from that bytecode on every request. This process is quite fast, but on high-traffic websites, it’s recommended that we cache the bytecode and skip script interpretation. This technique increases a website’s performance without requiring additional resources.

On Linux, accelerator modules that utilize these techniques, like APC and IonCube, are very common. These also work on Windows and could potentially also work on Windows Azure. However, Microsoft also released its own module that applies this technique: the WinCache extension for PHP. This extension is the fastest PHP accelerator on Windows, and also provides features like storing session data in this cache layer. The Wincache extension for PHP can be downloaded from http://www.iis.net/download/wincacheforphp.

CDN (Content Delivery Network)

When using Windows Azure blob storage, you’ll find that a full-featured content delivery network (CDN) is available as well. A CDN ensures that, for example, when a user downloads an image, that image will be retrieved from a storage server that’s close to that user’s client. This ensures that the download speed and latency are optimal, and the user receives the image very quickly.

With blob storage, enabling the CDN is as easy as clicking a button. After that, your public containers are replicated to the CDN, which allows your site’s users to retrieve files and resources as swiftly as possible!

Figure 4. Using the Windows Azure CDN

Using the Windows Azure CDN


Domain Name Mapping

With Windows Azure, your application will be assigned a domain name under the cloudapp.net domain—for example, myphpapp.cloudapp.net. I think you’ll agree that this isn’t the greatest URL. It gets even worse when you’re using blob storage for hosting files: myphpappstorage.blob.core.windows.net is, well, just plain ugly!

Luckily, all URLs in Windows Azure can be mapped a custom domain name. So, to map www.myphpapp.com to myphpapp.cloudapp.net, you just need to add a CNAME record to your name server. The same applies to blob storage: storage.myphpapp.com can be mapped to the very long myphpappstorage.blob.core.windows.net through the addition of a CNAME record to your DNS server.

Check Azure team member Steve Marx’s post on custom domain names for more on this.

Conclusion

In this article, we’ve taken a snapshot of the Windows Azure platform from a PHP perspective. While I’m slightly biased by having contributed to the Windows Azure SDK for PHP, I do think that the Windows Azure platform is a great choice for hosting PHP applications in a highly-scalable cloud environment. I also feel that there’s great value to be found in features like the Windows Azure AppFabric Service Bus. The bottom line is: I believe that Microsoft is doing their best in making PHP a first-class citizen on their cloud platform.

Another great resource related to PHP and Windows Azure is http://www.interoperabilitybridges.com, the website that lists all PHP and open-source projects from Microsoft.

Don’t forget to head over to our Microsoft-sponsored Article Quiz to test your learnings.

note: Microsoft: A SitePoint Business Partner

This article has been made possible with the support of Microsoft. We work closely with Microsoft to help develop the content that’s most useful and relevant to you—our readers.

Free book: Jump Start HTML5 Basics

Grab a free copy of one our latest ebooks! Packed with hints and tips on HTML5's most powerful new features.

No Reader comments

Comments on this post are closed.