Category Archives: PHP

ASP.NET/PHP on the Microsoft Web Platform Event in Ireland


I’m really looking forward to moving to Ireland and I’m going to hit the ground running…

Right off the bat I’m going to be throwing an event called the “Evolution of ASP.NET and PHP on the Microsoft Web Platform”. One of the reasons that we’re throwing this event when we are is that we have Ryan Ozimek coming over to help me reprise and enhance the WebMatrix launch event.

Abstract: Web development is continually evolving on the Microsoft Web Platform. This evolution has brought fantastic new features and functionality such as the new Razor syntax and ASP.NET MVC 3 on the ASP.NET side and WinCache and FastCGI on the PHP side. And great new tools such as WebMatrix and the Web Platform Installer make it exceedingly simple to download, customize and deploy many of the top OSS applications, such as DotNetNuke for ASP.NET and Joomla! for PHP, on Windows.

image004Amongst the speakers at this developer evening are Josh Holmes, the brand new Architect Evangelist for Ireland, and Ryan Ozimek, president of Open Source Matters which is the non-profit that takes care of Joomla!.

Join us for an evening diving into how web development is evolving on the Microsoft Web Platform. We’ll start with an overview of the entire platform and the recent flood of announcements. Then we’ll dive deep into the individual topics of the new ASP.NET Razor syntax, ASP.NET MVC3 and PHP on Windows.
Whether you are doing ASP.NET or PHP, whether you have years of experience with web development or are just getting started you’ll find just the right flavour of web development for you.

Date: February 8th, 2011. 6.30pm-8.30pm (registration from 6pm)


The Westin Hotel

35 – 39 Westmoreland Street
Dublin 2
Map: Click here for a map

Please join us for this event by registering online.

The talks will wrap-up after two hours, giving attendees plenty of time to have a drink and some food whilst networking or playing around with some of the latest Microsoft gadgets.


Rev it up with PHP and IIS

Slide1_thumb[1]Mark Brown and I did a talk at ZendCon last week on how well PHP runs in IIS and more specifically, some things that you should do in order to make it run really well on IIS.

Quick warning, this is an unfortunately bullet pointy slide deck for me. Mark created the original deck that this talk was born from but I’m responsible for delivering it at ZendCon and for posting it here. 🙂

Mark is with the Web Platform Team and a good guy to know. He saved my tail on this one. My voice was killing me and he stepped in and did 80% of the talking. I talked through the demos but he hit all of the talking points.


We started the talk off with a little walk down memory lane. The reality is that many people who have tried PHP on Windows and really didn’t like it did so on previous version of IIS under CGI. Issue was that PHP on older version of IIS with the old school CGI handler It wasn’t until 2007 when FastCGI came out that things started to get interesting on the IIS stack.


IIS 7 came out starting with Win7 and SQL Server 2008. It’s gotten a huge overhaul, not just in terms of PHP but terms of it’s entire architecture. To start with, the attack surface is greatly reduced as it does a very lightweight install and then you have to turn on anything that you want to run. Out of the box, it only serves up static files and you have to turn on ASP.NET, PHP and anything else.

The new modular architecture is fantastic. It used to be that you had to write any extension or modules in C++ or at least do a C++ wrapper around managed code. Now you can write your modules in .NET and load them directly. These modules can plug into any point along the processing pipeline and do anything from handling authentication to manipulating the incoming or outgoing streams.

Additionally the per application configuration has gotten tremendously powerful and can do anything from setting up the cache handing to URL Rewrite rules (more on this in a bit) to setting up the modules and handlers that can plug into the IIS processing pipeline.

Slide4Another great improvement is FastCGI. If you are doing PHP on IIS, you need to be using FastCGI. It is the CGI handler on IIS 7 and is available as a download for IIS 6. There were some really fundamental changes that were made. One of these is that under CGI, IIS spun up a new process for every request. This is a really expensive thing to do. Under FastCGI, it does some awesome things where it spins up a configurable number of processes and then recycles those same processes over and over again. There’s a ton of other great improvements here including recycling the PHP pool when the php.ini changes so you don’t have to manually restart IIS and much more.Slide5

WinCache is not installed by default on some IIS instances but you should check to make sure that it is. It’s distributed through Pecl at It provides a ton of great enhancements including Opcode Cache, File Cache, Relative File Path Cache, Session Cache and User Data Cache. The awesome part is that all you have to do to take advantage of the first 3 is enable WinCache in your PHP.ini file. Just doing this has shown anywhere from a 100% to a 400% increase in performance depending on the application and what it’s doing.

To take advantage of User Data Cache, you need to write a little bit of code but all of the functions have the same function signature as APC. See the little bit of code that had to be written for Joomla support for WinCache for an example.

Once you’ve installed it, there’s a great script that will help show you what’s in WinCache at any given point – more details at


URL Rewrite is a very powerful rewrite engine for IIS 7 so you no longer have to look at external rewrite engines such as ISAPI Rewrite. Remember that this is not installed by default as IIS 7 installs with the smallest set of features possible. If you’re an Apache user right now, the easiest way to get started is to simply import your .htaccess file and it will pull in and convert your rules to the web.config file that IIS 7 uses.

One quick example is the one that I use for WordPress to enable pretty urls.

<?xml version="1.0" encoding="UTF-8"?>
        <rule name="wordpress" patternsyntax="Wildcard">
          <match url="*" />
            <add negate="true" 
                 input="{REQUEST_FILENAME}" matchtype="IsFile" />
            <add negate="true" 
                 input="{REQUEST_FILENAME}" matchtype="IsDirectory" />
          <action url="index.php" type="Rewrite" />

But it can do much more than just dealing with simple redirection. It can match on wildcards, regular expressions and a ton more.

Slide7Another way to squeeze some performance out of PHP on Windows is to migrate to PHP 5.3. The builds of PHP 5.2 and previous for Windows are built with VC6 which is a 10 year old compiler. The new PHP 5.3 builds are built with VC9 which is a modern compiler with a lot of great optimizations. In addition, earlier versions of PHP on Windows did almost everything through a POSIX translation layer just to get it to work. The Windows support in PHP 5.3 has been rewritten to run natively on the Win32 APIs rather than having to go through the translation layer.

Now, if you really need to check out building your own Performance Guided Optimization build of PHP specifically for your box.


The next thing look at is the new PHP Manager released on CodePlex. The very short version is that it allows you to run different versions of PHP on the same server for different applications. It manages  the php.ini file and PHP extensions per application as well. You can even connect to it remotely through the IIS Remote Administration Tool so you no longer have to have write permissions on the PHP directory on the box to manage things.


Connecting to SQL Server has been a pain point as well for many years. In 2008, however, the SQL Server team released the new native drivers for PHP on Windows. Then this year (2010 for those those that are reading this later… 🙂 ), the SQL Server team released PDO support for PHP on Windows. Drupal 7 is actually already tested against this and ready to go.

The question was raised about when we’ll have Linux drivers for SQL Server and I’ll give the same answer here that I gave on stage. The SQL Server team has received that feedback and it’s on the radar. I don’t have any insight into the SQL Server team’s roadmaps or future plans and I have no idea if it will ever happen or when it would happen if it were on a roadmap somewhere but I do know that the SQL Server team has heard that request from multiple sources and they listen to their community. Is that non-answer enough for you? 🙂


Another really useful utility is the IIS Database Manager. The easiest way to install this is through the Web Platform Installer. This plugin to IIS Manager helps you manage your databases whether they are SQL Server or MySql. It actually looks in your web.config file for connection strings and will show those databases in the “quick open” area or you can browse to your database and open it specifically. This is not going to replace your favorite DBA tool but it will give you quick and easy access to do simple things remotely without having to crack open extra ports and all that.


Many of the most popular PHP apps out there run really well on IIS and are easily installed through the Web Application Gallery and the Web Platform Installer.

Get WordPress

Get Joomla!

Get Drupal

But don’t stop there, you can check out all of the applications in the app gallery until you find the ones that make the most sense for you.


In addition to all the work on the core language and getting it to run really well, Microsoft’s been working hard at making things like SQL Server reporting services work with the SQL Server Reporting Services SDK for PHP. PHP works really well with Silverlight as Silverlight does a great job with restful services as well as having the best video experience out there through the adaptive streaming technology. I was talking to a PHP developer at ZendCon who does a lot of video and his shop used to have to buy 5 or 6 different bit rate videos to cover the different bit rates that their clients needed and they had to store all of that video somewhere. Now with Silverlight, they buy one video and store one video and all of their clients are shown the correct bit rate for their connection.


We’ve been doing a ton with the PHP community. Many of the things that we talked about in this talk are out there at open source.

WinCache is on PECL and licensed under BSD.

WinCache support for Joomla! which we write is released under GPL 2.

SQL Server Driver for PHP is under Apache 2.0

I’m not going to drain the list but most of the work by the Interoperability Bridges team is released as open source.

We listen and interact on the PHP forums. Many of us can be found on IRC. We work with core team members from PHP and many of the top applications to help decide what are our next features, products and more. It’s been a really exciting ride the last 3-5 years here at Microsoft in the PHP and open source space.


The quickest and easiest way to get started with PHP on IIS is through the Web Platform Installer. This wizard style installer will let you pick an application and not only install that application but it will determine what the dependencies are for it, configure your web platform and install all of those dependencies. And it’s language neutral installing both ASP.NET and PHP applications easily.


In summary, PHP on IIS has come a long way in 5 years. It’s a viable choice not only for development but for production. Performance, stability, configurability and more have all improved dramatically through technologies such as FastCGI, WinCache, SQL Server and very importantly IIS 7. Check it out. I think you’ll be pleasantly surprised.

The quickest and easiest way to check it out is through the Web Application Gallery.


Check it out and let me know what you think.

ASP.NET and PHP On IIS Together

phpUntitledI got a question the other day about running both ASP.NET and PHP on the same server and whether or not it works. The short answer I gave is “Yes”. The longer answer, I’m going to give here.

In point of fact, both ASP.NET and PHP work really well on the instance of IIS. They can’t share  session state but otherwise it’s a very peaceful existence.

First of all, PHP runs really well on Windows and IIS. There’s a lot of stuff that you probably didn’t know about it. Mark Brown and I did a talk about that at ZendCon – I’ll do a full write up of that talk sometime soon.

There are a ton of great resources out there for running PHP on Windows very well.

Easiest way to install PHP on Windows
Official site for PHP on IIS – Lots of good walk throughs and how to guides here.
RuslanY’s blog about IIS, FastCGI, PHP and other interesting stuff.
Brian Swan’s blog about PHP, SQL Server and more.
PDO driver for Microsoft SQL Server
SQL Server Reporting Services SDK for PHP
PHP: WinCache
Performance improvement in Joomla using WINCACHE user cache – great info on leveraging user cache.
Interop resources from Microsoft and PHP
URL Rewrite module for IIS7

I could keep going but this post is about running both ASP.NET and PHP on the same IIS instance.

Mike Volodarsky wrote a great article on leveraging the integrated pipeline in IIS7 that included leveraging ASP.NET Forms Authentication to restrict access to a PHP application. I’m not going to rehash that entire article but rather recommend that you leverage the applications that are up in the Microsoft Web Application Gallery such as Gallery. These applications are really simple to get set up on IIS7 through the wizard style installer in the WebPI.  

The first scenario that we’ll look at is a PHP application running as a subdirectory on the same server as an ASP.NET application. The first thing I’m going to do is get an ASP.NET application up and running through the Web Platform Installer (WebPI). I’m going to use BlogEngine.NET this demo. If you don’t already have the Web Platform Installer, it’s easy to install by going to and clicking "Install” next to any of the applications that you want to install. If you already have it installed, simply launch the Web Platform Installer, find BlogEngine.NET and start the wizard.

firstIf you want the application to be the root of the web server, then on the page where it’s asking about location, clear out the ‘application name’ field. It makes sense once you see it but it took me a second the first time that I tried it. I already had all of the dependencies installed for BlogEngine.NET so the rest was just following the wizard.

secondOnce BlogEngine.NET is installed, I can browse out to it and make sure that it’s all working. I can, if I want, do some configuration and change the title, skin and the like. However, that’s not the point of this little exercise so I’m going to skip it for the moment.

Now I’ve got an ASP.NET application up and running as the root of my server. Now I need to place the PHP application on the box to show them running side by side. The quick one that I want to install is Gallery which is a well known PHP application that does a good job at photo galleries. There are a number of galleries listed in the Web Application Gallery but the one that we want is “Gallery”.

ThirdAgain, I’m going to install the application through the WebPI. I have most of the dependencies installed already but I’m going to use SQL Server because I’ve already got one application using it, I might as well use it for the other. That’s going to require me to install the Microsoft Driver for PHP for SQL Server 2.0 and it’s associate that helps with IIS specifically. The good news is that these dependencies are selected and installed automatically by the wizard. Once the WebPI installer finishes, click “Launch Website” and finish out the installer.

At this point I’ve got BlogEngine.NET running at http://localhost and Gallery running at http://localhost/gallery proving out scenario one where PHP can run in a sub-directory under ASP.NET. The opposite is true as well but unless someone specifically requests it, I’ll assume that you can switch this example around and do it the other direction where you have a primarily PHP site with a little bit of ASP.NET running on the same server.

These different applications can share HTTP Handlers, URL Rewrite Rules, security rules (as stated in Mike’s article) and a bunch of different aspects of IIS. What they can’t share out of the box is session state. ASP.NET can store session in a number of places, including SQL Server and theoretically it’s possible to write a custom PHP session handler that would read from that same store but I haven’t tried it so I can’t guarantee that it’ll work.

In future posts, I’ll take a look at integrating HttpModules and HttpHandlers into the PHP pipeline and see how that works. In the mean time, have fun mixing and mashing technologies.

Zend SimpleCloud and Azure

image I’ve been playing with Zend’s SimpleCloud API for the webcast that I’m doing with Zend today. I started with the Zend Framework Quickstart tutorial but changed out the backend to hit the Azure Tables and such (well kinda – I used Zend Studio 8 Beta 2 and didn’t use the ZF tool but I still created a little guestbook). I’m going to expand this example to include blob storage and queues as well in the near future but at the moment, I’m just going to hit the Azure Tables.

update – here are the slides for the presentation:

To get started, I downloaded and installed the Zend Framework CE 1.10 and Zend Studio 8 Beta 2. Then I downloaded and installed the Windows Azure SDK. imageThe last bit that I needed was the Windows Azure 4 Eclipse which will install inside of Zend Studio since it’s built on Eclipse. To install it, open up Zend Studio/Eclipse and select Help | Install New Software to open up the dialog. Then click Add… and fill in the location as Click OK, select the Windows Azure for Eclipse Toolkit and follow the rest of the wizard to install it. At this point, I’ve got all of the software installed that I need to install and am ready to start coding.

Creating the Project

Before I create the project, a quick tip is that it’s a lot easier to work with IIS if you move the your Eclipse Workspace to c:\users\public\ZendWorkspace (I’m on Windows 7 so that’s where my public documents are). One more quick step is that I give IUSER Read and Execute permissions on the workspace.

imageOnce I’ve moved my workspace, in Zend Studio, select File, New Zend Framework Project.

Name the project SimpleCloudDemo.

Select “Create new project in Workspace”. I tried creating the project on a local server to skip a few steps but that didn’t work so well as you have to be an administrator to write to the c:\inetpub\wwwroot location. Instead, we’ll just map a virtual directory in IIS in a few moments.

Make sure that Zend Framework default project structure is selected (should be the default).

Click Finish. This will create basic project structure that you’ll need to get started. The Zend Framework is a MVC style framework.

To finish setting up the project we need to include the framework bits and the API bits so that we have everything in a nice portable folder. Copy in the C:\Program Files\Zend\ZendServer\GUI\library\Zend directory to [project dir]\library.

Lastly, download the SimpleCloud Api from and unzip it to the [project dir]\library directory.

Mapping the IIS Virtual Directory

Now we want to be able to test and make sure that everything is installed correctly and that the project works. To do this, we’re going to map a IIS virtual directory.

image Open Internet Information Services (IIS) Manager and expand the tree on the left hand side until you find the default web site.

Right Click on the Default Web Site and select Add Virtual Directory…

Fill out the Alias with something simple to remember such as simpleclouddemo and fill in the Physical path with the directory to [your project directory]\public. Since I moved my workspace up above, the full Physical path that I entered is c:\users\Public\ZendWorkspace\SimpleCloudDemo\public

image Now, browse to the virtual directory at  http://localhost/simpleclouddemo.

The one other thing that I’ll do that’s IIS specific is create a URL_Redirect rule that will make sure that the Zend Framework actually gets all of the calls rather than the calls just going into the IIS bit bucket. The easiest way to do that is to create a file called web.config in the public directory.

<?xml version="1.0"?>
        <?rule name="Main URL Rewrite Rule" patternsyntax="Wildcard">
          <?match url="*" />
            <?add negate="true" input="{REQUEST_FILENAME}" matchtype="IsFile" />
            <?add negate="true" input="{REQUEST_FILENAME}" matchtype="IsDirectory" />
          <?action url="index.php" type="Rewrite" />

At this point you should have the project up and running. Now we’re ready to start slinging code.

Creating the Model and Azure Table

We’re going to dive right in and start creating the model and the Azure Table.

The first thing that we’re going to create is the Guestbook model class itself. Create a new PHP file named GuestBookModel.php in the /application/models directory as follows.

// application/models/GuestbookModel.php
class Application_Model_Guestbook extends Zend_Service_WindowsAzure_Storage_TableEntity
	* @azure comment Edm.String
	public $comment;	
	* @azure created Edm.String
	public $created;
	* @azure email Edm.String
	public $email;

Couple of things that are interesting here.

  1. Notice that the class extends (read inherits for those of you that don’t do PHP heavily) Zend_Service_WindowsAzure_Storage_TableEntity. This parent class gives us the other required fields such as a PartitionKey, RowKey, TimeStamp and the like.
  2. Next, notice the @azure comments in front of each of the variables. This gives typing information to the Azure Table storage engine for comparisons, sorting and storage optimization. The possible choices there are:
Property Type Details
Edm.Binary An array of bytes up to 64 KB in size.
Edm.Boolean A Boolean value.
Edm.DateTime A 64-bit value expressed as UTC time. The supported range of values is 1/1/1601 to 12/31/9999.
Edm.Double A 64-bit floating point value.
Edm.Guid A 128-bit globally unique identifier.
Edm.Int32 A 32-bit integer.
Edm.Int64 A 64-bit integer.
Edm.String A UTF-16-encoded value. String values may be up to 64 KB in size.

The next thing to do is create the GuestBookMapper in the application\models directory.

// application/models/GuestbookMapper.php
class Application_Model_GuestbookMapper
	protected $_cloudTable;
	protected $TABLE_NAME = "guestbook";
	protected $PARTITION_KEY = "guests";
    public function setCloudTable()
    	//This constructor takes account parameters for the live azure account
    	//Goes to Dev Storage if you don't pass in any parameters. 
    	$tableStorageClient = new Zend_Service_WindowsAzure_Storage_Table();
		$this->_cloudTable = $tableStorageClient;
        return $this;
    public function getTableStorageClient()
    	if (null == $this->_cloudTable) {
        return $this->_cloudTable;
    public function fetchAll()
    	$tableStorageClient = $this->getTableStorageClient();

        if ($tableStorageClient->tableExists($this->TABLE_NAME))
    		return $tableStorageClient->retrieveEntities($this->TABLE_NAME, "", "Application_Model_Guestbook");
    	return null;
    public function save(Application_Model_Guestbook $guestbook)
    	$tableStorageClient = $this->getTableStorageClient();
        if (!$tableStorageClient->tableExists($this->TABLE_NAME))
    	if ($guestbook->getRowKey() == null) {
    		$guestbook->setRowKey(uniqid ());
	$tableStorageClient->insertEntity($this->TABLE_NAME, $guestbook);

As you look at that code, there’s a couple of things to point out.

  1. I could pass in parameters to the constructor of the Zend_Service_WindowsAzure_Storage_Table constructor to give my account information for a Windows Azure storage account but if you don’t pass anything in it defaults to the dev storage account.
  2. In the fetchAll() function,  the second parameter being passed to the retrieveEntities function is a filter parameter. This is where you could pass in the search parameters and/or a partition to retrieve and so on. Regardless of what you pass in, the function attempts to match on those items and returns a collection of items that match.

The next thing is to create the GuestBookController.php in the application\controllers folder.

 * GuestbookController
 * @author
 * @version 
require_once 'Zend/Controller/Action.php';
class GuestbookController extends Zend_Controller_Action
     * The default action - show the home page
    public function indexAction ()
        $guestbook = new Application_Model_GuestbookMapper();
        $this->view->entries = $guestbook->fetchAll();
    public function signAction()
        $request = $this->getRequest();
        $form    = new Application_Form_Guestbook();
        if ($this->getRequest()->isPost()) {
            if ($form->isValid($request->getPost())) {
                $comment = new Application_Model_Guestbook();
                $comment->comment = $form->getValue("comment");
	       $comment->email = $form->getValue("email");
	       $mapper  = new Application_Model_GuestbookMapper();
                return $this->_helper->redirector('index');
        $this->view->form = $form;

Couple of things to point out here as well.

  1. In the indexAction, the fetchAll() call returns the list of entries as a collection and  hands it off to the view.
  2. In the signAction, we’re using the Application_Form_Guestbook which we are about to create. It’s got a little bit of validation but I wouldn’t rely on just that for my business logic but I’m a belt and suspenders kind of guy when it comes to data validation.

The next step is to create the Guestbook.php in application\forms directory.

class Application_Form_Guestbook extends Zend_Form
    public function init()
        // Set the method for the display form to POST
        // Add an email element
        $this->addElement('text', 'email', array(
            'label'      => 'Your email address:',
            'required'   => true,
            'filters'    => array('StringTrim'),
            'validators' => array(
        // Add the comment element
        $this->addElement('textarea', 'comment', array(
            'label'      => 'Please Comment:',
            'required'   => true,
            'validators' => array(
                array('validator' => 'StringLength', 'options' => array(0, 1000))
        // Add a captcha
        $this->addElement('captcha', 'captcha', array(
            'label'      => 'Please enter the 5 letters displayed below:',
            'required'   => true,
            'captcha'    => array(
                'captcha' => 'Figlet',
                'wordLen' => 5,
                'timeout' => 300
        // Add the submit button
        $this->addElement('submit', 'submit', array(
            'ignore'   => true,
            'label'    => 'Sign Guestbook',
        // And finally add some CSRF protection
        $this->addElement('hash', 'csrf', array(
            'ignore' => true,

The only thing to point out here is that this is a standard Zend Framework form.

The last thing that we absolutely need to do is create the two views, one for viewing and one for signing. The first one that we’ll create is index.phtml in application\views\scripts\Guestbook

<!-- application/views/scripts/guestbook/index.phtml -->
<p><a href="<?php echo $this->url(
'controller' => 'guestbook',
'action' => 'sign' ),
?>">Sign Our Guestbook</a></p> Guestbook Entries (<?php echo count($this->entries) ?>): <br /> <table>
<?php foreach ($this->entries as $entry): ?>
<td><?php echo $this->escape($entry->email)?></td>
<td><?php echo $this->escape($entry->comment)?></td>
<?php endforeach ?>

And next we’ll create the sign.phtml in application\views\scripts\Guestbook.

<?!-- application/views/scripts/guestbook/sign.phtml -->
Please use the form below to sign our guestbook!
echo $this->form;

There are other things that we could do but that all that we need to do for the moment. I’ll extend this example in the future.

Now, if you run the application and browse to http://localhost/simpleclouddemo/guestbook

If you get the error “Application errorexception ‘Zend_Http_Client_Adapter_Exception’ with message ‘Unable to Connect to tcp:// Error #10060: A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond.” – it’s because you need to launch the Development Fabric and specifically start the storage bit.

Once that’s done, you should see the guestbook as follows:


Then you can sign the guestbook as follows:


And then it will redirect you back the guestbook which will look as follows:


This is the bulk of what I demoed during the webinar. I’m going to continue to expand this demo as time goes on

Webinar on Oct 20, 2010 with Microsoft/Zend

imageI’m looking forward to starting this new webinar series that I’m launching in partnership with Zend about running PHP in general and Zend in particular on Microsoft Azure.

My goal, as I’m writing the demos today after posting this, is to go through the Zend Guestbook quick start and then port that to run in Azure and leverage that platform. I’ll be posting the full technical write-up here once I get done.

From the Zend web site:

Join a webinar on Cloud Computing with Zend Framework and Windows Azure. In this session, we’ll take a technical overview of Windows Azure Data Storage which can be used both inside and outside of your cloud application and the Windows Azure computing which can be leveraged to scale your application horizontally. We’ll write a small application with the Zend Framework and get it up and running in Azure so that we can dive deep into the individual parts in future webinars.
Join this webinar to learn how to take your application to the next level.


It’s important to note that this is the first of a series so we’re going to do an overview across the board this time and then we’ll dive deep into things such as the data access layers or architecting for scaling horizontally across multiple instances in the future.

Scaling WordPress on Microsoft

image I just finished doing a talk at in Dallas called “Scaling WordPress (and really any PHP application) on Microsoft. The reality is that there is a tremendous amount of support for WordPress on the Microsoft stack including Windows, IIS, SQL Server, Azure and more. was a an interesting conference and interesting crowd for my session. The idea behind is to get all of the big CMS options under the same roof and cross pollinate. This included WordPress, Joomla! and Drupal from the PHP side of the house, DotNetNuke and SiteFinity from the .NET side of the house and Polux from the Python side of the house. It was an interesting mix. I was a little nervous that it would just be a giant argument. While some of that did happen, I actually had a few people from Drupal and Joomla! in my WordPress session and people were fairly civil the whole weekend. image

Getting to the session

Now, on to my session itself. This was a fun session. I only had 30 minutes and I had about 3 hours of material so I’ve got a ton of stuff in these notes that I didn’t cover in the session itself.

The session is a take off a session that I did at MODxpo back in the spring. The talk itself is about 3-5 minutes of slides and the rest is all demos. Really, there’s not time to do all of the demos that I’d like to do. I could spend 3-5 hours doing demos if they’d let me. I’d love to get up and sling a lot more code than I normally get to in a conference session and really dig deep on the tech side.

The slides are up on SlideShare but here at the talking points

imageThe most important slide in the deck is my contact slide which has my email address and such on it so that people can reach out to me with any questions.

I love getting follow up questions after a session because it proves to me that people were listening and not just hiding from the Texas heat in my room.

image Microsoft is a software company that builds a lot of great platforms and applications. We have a large number of finished applications such as Microsoft Word and so on that a ton of people use out of the box every day to accomplish their job. But one of the exciting parts about Microsoft is that almost everything starting with Windows, SQL Server and so on all the way up to Microsoft Office is also a platform that other people (read you in the audience) can write applications on top of in addition to just using out of the box. The conglomeration of platforms from Microsoft that I’m talking about today is Windows, IIS, SQL Server and Azure and running PHP/WordPress on top of those platforms.

Looking Back

image Before we get to that, however, we need to take a quick peek back in history. Many of you probably tried PHP on Windows at some point in the history so you’re thinking that I’m crazy to attempt PHP on Windows. The reality is that in the past you might have been right.

image 5 years ago, PHP did not run on Windows all that well. It was slow. PHP wasn’t optimized for Windows/IIS and Windows/IIS wasn’t optimized for PHP. Painfully slow at points.

image It wasn’t compatible with the other versions of PHP. If you were on Windows vs. Linux, you had to take that into account when you were writing your applications and there were standard switch blocks that you’d have to code in order to accommodate the different platforms. Most people didn’t bother doing that so there was platform lock in which defeats much of the purpose of running PHP.

image There wasn’t a good implementation of mod_rewrite or a good alternative. This cause all kinds of problems with SEO optimization and much more.

image There were many other problems and it just made the PHP developers (understandably) mad at Windows and Microsoft.

image So where are we now?

image Microsoft has invested a tremendous amount of time and resources into making sure that we fix all of those issues.

image PHP on Windows is fast. FastCGI support for IIS 7.0, 6.0, 5.11 rocks and is fast. It’s the default on IIS7 and it’s a fast and reliable way to run PHP on Windows. Additionally, there’s a fantastic opcode and object cache library called WinCache that is distributed with PECL. More on this in the demos.

There are all kinds of benchmarks out there but I’d like for you to test it yourself. There are many areas where PHP on Windows/IIS is just as fast or faster than PHP on Linux/Apache. There are other areas where performance suffers some. You should test your application on both platforms and compare performance. For some applications you’ll be pleased, for others you won’t be. Either way you’ll learn something about your application.

image PHP on Windows/IIS is compatible because it’s the same PHP. This means that most of the applications should just run on IIS. Where there are incompatibilities, it’s because there are some extensions and such to PHP that don’t run on IIS because they are deeply embedded in the Apache piping system or they leverage something in Linux and so on. In some cases there are compatible alternatives. In other cases, we’ll have to work around those. If you run into one of these cases – PLEASE reach out to me and let me know what you’re trying to accomplish.

image A great example of where we don’t have the exact same thing but a great alternative is mod_rewrite on Linux and URL Rewrite on IIS. I’ll walk through a demo of this in just a little bit but in short, URL Rewrite is a fantastic and powerful engine that allows you to do some outstanding things.

image More pigs fly – we didn’t stop there. In June 2009, we contributed 20k lines of source code to the Linux kernel to do much better virtualization support for things such as Suspend, Hibernate and Resume. Obviously our motivation was to get it to work better with Hyper-V but that code also helps with VMWare, Parallels and more.

Getting to the Demo

image Now, all of that is fantastic but let’s get to some demos. Demos are the meat of this talk.

image ‘Cause I think that you want to see what’s in my smokin toolbox here and seeing is believing.

Web Platform Installer

imageThe first thing I need to do is get WordPress up and running on my Windows installation. The easiest way to do that is with the Web Platform Installer. This is a free tool that Microsoft has put out there to make your life easier on IIS. You can, under the Web Platform Tab, configure your server to install modules such as URL Rewrite, Advanced Logging features, ODBC or any number of things that are optional on IIS but you might need to leverage.

But the tab that we’re most interested in is the Web Application tab where you can find WordPress. Under this tab you’ll find a bunch of different applications ranging from Aquia Drupal to DotNetNuke to Moodle to ScrewTurn Wiki to WordPress.

All of these applications and all of this data actually comes from the Web Application Gallery.

image If you select WordPress and click Install, you’ll get the installation wizard which will analyze the requirements for the applications and make sure that you have everything and download it if you don’t. An important thing to notice here is that the WordPress install is actually coming from If you’ll notice, that’s actually coming from the WordPress foundation rather than from Microsoft. We’re not distributing WordPress or any of these projects. Instead, we are providing a channel and portal for those applications with a lot of support to make sure things are tested and ready to go.

image The next couple of screens that we see are configuring your specific installation. The first screen is a common screen that all of the projects get that has to do with were you’re going to put the physical files and the virtual directories stuff that IIS cares about. If you are running multiple web sites off of one machine, here’s where you make that assignment. For example, I’m running and off of the same server

imageThe second page is actually configured by the project itself and has to do with the project’s configuration files directly. WordPress, for example, needs to know the MySQL Administrator’s password so that it can log into MySQL and create the database. It also needs to create a user for that database it set it’s password and the like. This is all part of the package that was downloaded from

Investigating the WebPI Package

image That package is just a ZIP file with the PHP files, SQL Scripts and a couple of XML files in it. If you open the ZIP file and look at the parameters.xml file, you’ll see how this is all built up. For example, there’s a custom parameter called DbName with a default value of “wordpress” that’s got a regular expression validation of “^\w{1,16}$” or in English, 1 to 16 characters in length with no whitespace or punctuation. This parameter file is inserted into the install.sql file wherever the Web Platform Installer finds the word “PlaceholderForDbName” and in the wp-config.php file where if finds “putyourdbnamehere”. This makes it easy to set up any parameters that you want and insert them into any file that you want. And if you want, you can create your own projects and custom feeds for the Web Platform Installer to leverage. I’ll have to write an article about doing that in the near future.

The next thing that happens is that the install is done and you’re ready to start setting up your WordPress install. You should be, if you’ve ever set up WordPress on any platform, be familiar. You have to make sure that you copy that fantastic auto-generated password, log in and immediately change your password so that you don’t forget it.

An important thing to point out here is that even though it’s an older version of WordPress that’s installed, it’s still WordPress and WordPress can update itself and you should do that if you are going to run this for more than a quick demo.

Pretty URLS and URL Redirect

image The next thing that I want to do is set up my navigation and URL redirection. Just like any other WordPress install, you can do that under Settings | Permalinks. Select your favorite configuration and once you save your updates, there’s a prompt that tells you “You should update your web.config now”. If you’ve done this on Linux, you’ll get a prompt that says “You should update your ht.access now”. This is because URL Rewrite leverages the web.config. You can actually, if you’ve got an ht.access file that you use all the time, import that directly through the Internet Information Services Manager. The web.config is an XML file that has a tremendous amount of power. In this file you’re able to create file handler mappings, security settings on a per directory level, FastCGI settings, default documents for the application, IIS modules and a ton more. The web.config that WordPress requires at a minimum for pretty URLs is as follows:

<rule name=”wordpress” patternSyntax=”Wildcard”>
  <match url=”*” />
      <add input=”{REQUEST_FILENAME}” matchType=”IsFile” negate=”true” />
      <add input=”{REQUEST_FILENAME}” matchType=”IsDirectory” negate=”true” />
  <action type=”Rewrite” url=”index.php” />

Save this as a file called web.config in the root directory of your web application and you’re good to go with pretty URLs.

Quick Peek At WinCache

The next thing that I want to look at is WinCache. WinCache is a library written by Microsoft and distributed through the PECL Foundation. It’s a op code caching and object caching library that is on by default in the PHP install from the Web Platform Installer. To demo this I turned off WinCache in the php.ini file and used a little client app called WyCats that spins up 25 threads and starts hammering the server. It measures the number of requests, responses, errors and the like. Then I turn WinCache back on and restart WyCats. Immediately there’s a 3-4x improvement in performance. We could go a lot deeper with WinCache but that’s a topic for a different blog post.

Windows Azure Data Storage

This helps you scale vertically on a single box but to get true scale, we’re going to need to start leveraging horizontal scaling. One of the easy things to do is leverage a WordPress Plugin called “Windows Azure Storage for WordPress” which will offload the use generated media such as pictures, media files and anything else heavy to the Azure Data Storage which can be put out on the new Azure Content Delivery Network. That’s got a global footprint and helps you put your content near to your reader.

More WordPress Plugins that Rock

There are a lot of other WordPress plugins that leverage various parts of the Microsoft ecosystem including the Bing 404 plugin, the Bing Maps plugin, the Silverlight Streaming Media plugin and more. I’m pretty excited about all of these plugins.

  • The Bing 404 plugin handles broken links and will do a Bing search of your site suggesting possible updated links. This one was written by Cal Evans of Blue Parabola.
  • There are actually three different Bing Maps plugins. The Silverlight Bing Maps plugin is awesome, even if all of the comments are written in French. It helps you drop a Bing Map anywhere on your site with the use of shortcodes.
  • The Silverlight Streaming Media leverages the Smooth Streaming support in IIS to intelligently stream the media at the appropriate fidelity for your consumer based on their bandwidth,  machine specs and the like.

All of these plugins are obviously released under GPL since they are hosted on the site and easily found through the add new plugin search.

Windows Live Writer

One of the things that I didn’t plan on hitting on but decided to after I saw that there was a fair number of bloggers in the room that weren’t as technical is Windows Live Writer. It’s a free tool that allows you to do your blogging and posts in a desktop application so you can do it offline and have all of the richness of a desktop application. It’s got preview states where it will actually show your blog post as you’re writing it as it will look on the page complete with margins, your CSS and the whole nine yards. There are hundreds of fantastic plugins to do everything from inserting maps to formatting HTML code to managing flickr images.

It’s the tool that I use to do all of my blogging. This post, as an example, I wrote in three different airports, on two different planes and I’m in my hotel room at the moment finishing it up.

Between WordPress, Windows Live Writer and Jing, I’m a happy blogger.

SQL Server Support!

image Ok, back to the slides for a bit.

Another thing that’s very exciting is SQL Server support is available right now. This is not in core yet but we’re hoping that we can get it accepted at some point in the near future.

imageNot only that, but there’s a new PDO driver for SQL Server so that any code that leverages PDO (such as Drupal) can have SQL Server support if you’re using SQL statements that are supported by SQL Server. For example, if you’re using LIMIT statements as an integral part of your business logic, we’ll need to figure out a workaround.

Free Stuff

Now, if any of this interests you we’ve got a number of different offers to that fit a variety of options for getting you software, marketing support and more from Microsoft.

Before we even talk about the *Spark solutions, there are a ton of tools and applications that are free from Microsoft.

  • Web Platform Installer – I already talked about this a ton.
  • Visual Web Developer Express – This is a fantastic web dev toolkit that includes code editing, debugging support and more.
  • SQL Server Express 2008 – This is actually a really powerful option as a free database option. It supports up to a 10 gig database, transactions and the whole nine yards. The features that it doesn’t include are in the enterprise features such as Reporting Services and the like.
  • Windows Azure SDK for PHP – This fantastic SDK gives you access right in PHP to all of the Windows Azure Data Storage options and much more.

The list is actually REALLY long but this isn’t the focus of this blog post and I didn’t really spend a ton of time on it in my talk cause I didn’t have time.

DreamSpark is for Students. This gives you access to many of our professional tools and the like for you to leverage. There are also fantastic student discounts on Microsoft software for students. DreamSpark is completely free of charge.

WebsiteSpark is for small shop web consultants. The definition of that is anyone whose company is less than 10 people (yes – individual consultants count in this definition) and the company creates net new web sites for other people and companies. What this gives you is 3 copies of Visual Studio Pro and Expression Web, a copy of Expression Blend, production licenses for Windows Server and SQL Server Web Edition, entry into the Microsoft Pinpoint tools which drives business to local Microsoft partners and more. There are no upfront costs and at the end of three years, Microsoft will invoice you for $100.00. Other than that, it’s free of charge.

BizSpark is for technology startups. The definition of a technology startup for the purposes of this program is less than 3 years old, less than one million in revenue a year, privately held and creating software or software as a service. This gives the startup 25 licenses for MSDN which gives the developers pretty much any thing that they can build an application on top of. There’s also marketing support and such that can be leveraged through this program. There are no upfront costs and at the end of three years, Microsoft will invoice you for $100.00. Other than that, it’s free of charge.

I strongly encourage you to look at the various spark programs and see if there’s one that fits you.

More Azure Support

image Don’t know if you know this but, which is running in Azure itself and leveraging the SQL Server support and the Azure Data Storage options with SQL Server. We’re working making that more broadly available so that sometime soon you could run in Azure as well. The awesome part about that is that it will allow you to scale up very quickly to meet market demands without having to think about infrastructure.

Lots of Resources

Web Platform Installer

How WinCache makes PHP run faster

Using WinCache Extensions for PHP

Changes Made to PHP 5.3 to Support Windows

Migrating from PHP 5.2.x to PHP 5.3.x

SQL Server PHP Blog

SQL Server Support for WordPress

Microsoft’s WordPress Site on

Microsoft’s Official WordPress Landing Page

Josh Holmes’ Blog


To wrap up the talk and this blog post, PHP on Windows works really well and there’s lots of great support for all of the major PHP CMS/blogging engines including WordPress, Drupal and Joomla!.

I had a ton of fun at and hope to go back if they do it again next year. I’m hoping that next year I can do a full on hour of deep dive technical stuff that will really hit that ninja level that I wanted to cover. As you can tell, I brought way too much material but amazingly I actually hit my time mark perfect (I’ve been working on that).

CTP 2 of Microsoft Driver for PHP for SQL Server Released!

I was planning on writing up a long blog post about the CTP of the Microsoft Driver for PHP for SQL Server driver but Brian Swan already did a fantastic job complete with code. Quick snippet from his post:

Here’s a high-level list of the work that was done for this release:

  • Code refactored to share common functionality between the SQLSRV and PDO_SQLSRV drivers.
  • SQLSRV extension is rebuilt with refactored code (no new features).
  • PDO::__construct(): a design change from CTP1, Connection Options now need to be specified in the DSN string instead of the driver_options[] array.
  • PDO::SQLSRV_ATTR_DIRECT_QUERY: new custom driver attribute to provide more flexibility to the developer.
    • Ability to execute two queries within the same context or different contexts (useful for using temp tables and other features that are not always available with prepared statements).
  • Error messages are now encoded per the setting of CharacterSet / PDO::SQLSRV_ATTR_ENCODING.
  • Bug fixes to both the PHP_SQLSRV and PDO_SQLSRV extensions.

My thought on this is that it’s another great step in Microsoft’s working with the PHP community. A colleague actually asked “Am I right we are picking up the tempo in terms of PHP related activity?". I was able to answer with an enthusiastic “Yes”. 🙂

Make sure to check out Brian’ Swan’s Post at CTP 2 of Microsoft Driver for PHP for SQL Server Released.

Resolving PHP Version Conflicts while Developing for Azure

A little while back I wrote a blog post titled Easy Setup for PHP On Azure Development. One of the things that I touched on is the PHP version conflicts. I had a much better idea which I’ve tried and have working so I thought I’d blog that here. What I had you doing in the Easy Setup for PHP On Azure Development is renaming the directory for PHP from something like C:\PHP or C:\Program Files\PHP to something else so that it wasn’t in the %PATH% so there wasn’t a conflict.

The Fix

Reality is that we don’t have to do that. Instead, we can all co-exist happily on the same box. In short, what we’re going to do is load the local version of PHP from our box into the dev fabric rather than using the one that’s bundled with the Eclipse plug-in. The way that we’re going to do that is by using the web.config to specify the location on the local disk where our PHP install is.

That web.config looks something like this:

<?xml version="1.0"?>
    <!-- DO NOT REMOVE: PHP FastCGI Module Handler -->
      <clear />
      <add name="PHP via FastCGI"
           scriptProcessor="c:\program files\php\php-cgi.exe"
           resourceType="Unspecified" />
      <!--add name="PHP via FastCGI"
           resourceType="Unspecified" /-->
      <add name="StaticFile" path="*" verb="*" modules="StaticFileModule,DefaultDocumentModule,DirectoryListingModule" resourceType="Either" requireAccess="Read" />
    <!-- Example WebRole IIS 7 Configation -->
        <clear />
        <add value="index.php" />

Notice that I’ve commented out the original handler that setup the processer with the %RoleRoot%\approot\… We’ll need that when we go live but for now, we’ll use the one that’s actually using the hard path on my local disk.

The exciting part about it is that we’ll be able to use our own version of PHP with all of the extensions that we normally use and configured exactly to taste.

Testing Local

The other exciting thing is that you can actually test any of your WebRole code against your local IIS rather than having to deploy it to the DevFabric every time you want to test. Deploying to the DevFabric takes time and so I’ve found myself taking more time and slinging just a little more code than I should before doing my testing. Against my local IIS box, I’m able to just refresh the browser and see instant results. I still definitely recommend running in the DevFabric because it’s as close to the real environment as you’re going to get at the moment.

image To test against your local IIS with the same exact source code and folders, simply set up the directory as a Virtual Directory. To do that, you need to do one of two things. You can open up the IIS manager and add it that way or you can use Powershell to do it.

In IIS manager, expand the navigation tree down to find the web site that you want to deploy your virtual directory on (typically this is “Default Web Site”) and right click. Then select Add Virtual Directory and fill out the wizard with the alias (e.g. myproject will end up with http://localhost/myproject) and the physical path that you want to use.

If you decide to go with the PowerShell option and do it from the command line, there’s a great cmdlet (Powershell script) called New-WebVirtualDirectory that you can leverage. Make sure that you read the instructions on how to Import All Modules.

The Catch

Now, the issue that you’ll have with this is that when you do actually go to deploy to the cloud, you’ll need to either retest with the version of PHP that’s bundled by default by the Eclipse tooling or make your deployment package by hand with the command line tools.

My recommendation is rolling your own package with the command line tools. Really all you need to do is use CSPack (and possibly CSRun to test locally) from my blog post at Windows Azure Command Line Tools.

Additionally, The great news there is that there’s some great tools available for you at

Wrap up

I’m much happier with this solution than I was with the whole renaming the directory hack. It worked but it was a pain when switching between regular and Azure development. This way, regular and Azure development are seamless.

phpBB is in the Web Application Gallery

image You might have seen me tweet about the fact that PHPBB had submitted to the Web Application Gallery a couple of weeks back. Well, it’s official – the phpBB package has been finished, tested and accepted into the Web Application Gallery. You can see the official announcement on the Microsoft Web Platform blog. That means that you can install phpBB on Windows through the Web Platform Installer (WebPI) which gives you a very simple wizard to walk through.

Try phpBB on the Microsoft Web Platform today!


The WebPI will take a look at the dependencies that the project has requested and pull those in as well. In the case of phpBB, this includes PHP 5.2.13 (and higher when the WebPI supports it), SQL Server (Yes, I said SQL Server!) and more. It will configure IIS for FastCGI support and the whole nine yards.

The work to accomplish all of this awesome support was done at JumpIn Camp by Nils Aderman, Chris Smith and Henry Sudhof of the phpBB core team. I’ll be talking a lot more about JumpIn Camp over the next couple of weeks but in short, JumpIn Camp was an event that I helped organize, along with Yuriy Zaytsev, Will Coleman and Bram Veenhof in Zurich, Switzerland. There were contributors from a number of the top PHP applications in the world that attended for the opportunity to work on their own projects to support various Microsoft technologies (such as IIS, WebPI, SQL Server, SQL Azure, Silverlight…) with Microsoft technology experts available for technical support.

The SQL Server patch was developed by Microsoft in line with our interoperability efforts in the open source community. The new SQL Server for PHP 1.1 driver that was released back in October, 2009 enables phpBB with UTF-8 on SQL Server, Multiple Active Record Sets (MARS) and the ability to leverage SQL Azure. phpBB has accepted that patch now in their 3.0.7 release.

There are a couple more things that are exciting about all of this to me.

First, it only took a handful of days at JumpIn Camp to pull together the WebPI package + WinCache support for superior performance on Windows. For full disclosure there was some testing and a few minor bugs fixed since then but the lions share of the work was done at JumpIn Camp.

Second, phpBB is the first of the PHP application that can be installed through the WebPI with SQL Server support. I’m hoping that it will become the trend now that the SQL Server Driver for PHP 2.0 CTP with PDO is in CTP and people can start playing with it. I know that there are several applications that are starting testing with the new driver.

Third, it was a ton of fun to get to know the folks from phpBB and all of the folks that attended JumpIn Camp. I’ve been chatting with Nils online for about 6-9 months now but this was the first time that I had met him in person.

Wrapping up – I’m looking forward to seeing a lot more of the work that came out of the JumpIn Camp wrapping up and going public over the next handful of months. It’s going to be a fun time.

PDO Driver for SQL Server CTP

The SQL Server team had a great announcement yesterday at DrupalCon in San Francisco. They announced the availability of a PDO Driver for SQL Server to give fantastic access to SQL Server from PHP. PDO is the PHP Data Objects extension that has become the standard way to do data access in PHP 5.0 or later projects that want to have some level of database agnosticism. Drupal, for example, uses the PDO driver for all of it’s database access.

The rough architecture for the 1.1 and 2.0 SQL Server drivers is outline below.


In short, they centralized a lot of the core functionality into a common layer and have fairly thin wrappers over the top of that for the native and PDO drivers. This means that both will perform equally.

The great news for anyone who has written their applications with PDO rather than native drivers for a given database is that they should be able to plug in the new SQL Server PDO driver and start testing.

To be absolutely clear, however, PDO is not a full database abstraction. It doesn’t rewrite SQL statements of abstract away concepts such as MySQL Limits and the like. If you are using database specific features like that, you will have to rewrite those bits in your project.

See the official announcement on the SQL Server team’s blog at Interoperability @ Microsoft : SQL Server Driver for PHP 2.0 CTP adds PHP’s PDO style data access for SQL Server