Using Guzzle to Interact with the Windows Azure Management API

Guzzle is a very simple abstraction over cURL which provides a great HTTP client for working with web services. This provides a great way of interacting with the Windows Azure Management API with PHP. In this example, I’m going to show how you can enable and disable an SSL Certificate in a Windows Azure Web Site using the Windows Azure Management API.

The majority of Windows Azure Web Site tasks can be automated using either the Windows Azure PowerShell cmdlets or the Windows Azure Cross Platform Command Line tools. This includes the ability to upload an SSL Certificate for your Web Site, however at this point there is no ability to bind the SSL Certificate to the Web Site itself. That’s where Guzzle and the Windows Azure Management API come into the picture.

You can do the following exercise from the Windows Azure Management Portal by following the instructions in the article Enable HTTPS for a Windows Azure web site. This entry is to demonstrate how you can achieve SSL Certificate binding as part of an automated environment script.

Automating SSL Certificate Upload to Azure Web Sites

Before we start interacting with the Management API let’s get the Windows Azure Web Site ready by adding the SSL Certificate to the Environment. This task is incredibly simple to accomplish using the Windows Azure Cross Platform tools.

SSL certificates can be uploaded only in Standard mode. Learn more about configuring custom domains.

azure site cert add [ssl-cert-path].pfx --key [cert-password] [web-site-name]

That’s it! The cert will now be added to the Windows Azure Web Site.

Create and Upload Export a Windows Azure Management Certificate

You could very well create and upload a management certificate of your own by creating one with OpenSSL and uploading it via the Windows Azure Management Portal (Settings > Management Certificates). However, there is a much easier way to achieve this without having to generate your own certificates, by using the Windows Azure Cross Platform Tools.

azure account cert export [--subscription]

The optional subscription parameter can be either the name of the subscription name or id from the azure account list command output.

Create a PHP Application with Guzzle to interact with the Windows Azure Management API

This is where things get fun! Let’s start by creating a composer file to acquire Guzzle.

Next we’ll want to take a look at the documentation for how to Enable or Disable SSL in Windows Azure Web Sites with the Management API. This gives us the information for the rest endpoint, http verb and xml/json payload to enable or disable the SSL Certificate.

Warning! At the time of writing SSL Certificates are only available for upload/binding if the Web Site is in Standard Mode. If the site isn’t in Standard Mode your requests will return with the status code HTTP 400 Bad Request.

Enable SSL JSON Playload

Disable SSL JSON Playload

PHP Source Code

To enable or disable SSL in a Web Site you will need to make a PUT request against the management API pass in your SubscriptionId, the webspace of the site, the site name and the Client Certificate. In Guzzle the request is constructed by the client, which you can pass an array of values into for replacement when you create the request by calling the PUT method.

Conclusion

This is how simple it is to make calls to the Windows Azure Management API from PHP using Guzzle. This blog post covers the usage of JSON for the request payload, however, there is a full example available as a Gist if you’d like to see how this can be done with XML.

Deployment Time Dependency Management for PHP with Composer on Windows Azure Web Sites

Windows Azure Web Sites provides the ability to manage dependencies on deployment for .NET using NuGet, and Node.js using npm. This functionality is facilitated by an open source project called Kudu which is built and maintained by the Windows Azure Web Sites team [it can also be installed on Windows Server 2012].

If you’re a PHP Developer, you should know about Composer. Wouldn’t it be great if you could use Composer on Windows Azure Web Sites to fetch your dependencies during the deployment of your PHP Application? I thought so too!

To get started, I would recommend following this tutorial to create a php web site using the windows azure command-line tools for mac and linux. It’s ok, I’ll wait… Oh, back so soon? You should now have a Windows Azure Web Site with Git Deployment enabled.

Customizing a Windows Azure Web Sites Deployment for PHP

The Windows Azure Cross Platform Command Line tools expose an extended part of the Kudu functionality called KuduScript. KuduScript can be used to generate a set of files (.deployment, deploy.cmd) which hooks a Kudu deployment, enabling a custom script to be run at deployment time.

To generate a deployment hook with the Cross Platform Tools, run the following command:

azure site deploymentscript --php [-t bash]

This will generate a deployment hook for a PHP application, you could optionally pass in –t bash which would output the script in bash instead of the default batch.

Now that we have a customized deployment script, let’s add a few customizations; one to download composer to our Windows Azure Web Site, the second to run composer to fetch our dependencies specified in our Composer.json file. Add the following two lines above the Deployment section of the deploy.cmd.

::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
:: Download Composer
:: -----------------

echo Downloading Composer

IF NOT DEFINED COMPOSER_VENDOR_DIR (
	SET COMPOSER_VENDOR_DIR=%DEPLOYMENT_TARGET%\vendor

	echo Downloading Composer

	curl -sS https://getcomposer.org/installer | php

	IF !ERRORLEVEL! NEQ 0 goto error
)
php -d extension=php_intl.dll composer.phar install --prefer-dist --no-dev --optimize-autoloader

Debugging Deployment Issues

Now that you’ve added a process to your deployment that has an external dependency there will most likely come a time where you will need to diagnose issues with your custom deployment. Not to worry, Windows Azure Web Sites includes the output of the deployment script in the Windows Azure Management Portal. To view the deployment log:

  1. Click into the details view of your Windows Azure Web Site
  2. Click on the DEPLOYMENTS tab
  3. Click on the top item in the Deployment History section
  4. An arrow will appear to the right of the entry, Click the Arrow.
  5. Click on the View Log link

waws-deployment-hook-debug

Moving the Web Root in Windows Azure Web Sites

A common practice in PHP is to have the vendor directory which is created by running composer be a sibling of the web root directory. This provides a level of security as the vendor directory is not stored in a publicly accessible location avoiding public calls into third party code downloaded by composer.

This can be achieved in Windows Azure Web Sites by changing the Virtual Directory of the web root from within the Windows Azure Management Portal. Assuming my application serves it’s public content from a folder called web contained in the root of my source control, the following steps will move the web root to the web directory:

  1. Click into the Details of your Windows Azure Web Site
  2. Click on the CONFIGURE tab
  3. Scroll to the bottom of the CONFIGURE screen until you find virtual applications and directories
  4. Change the record for / from site\wwwroot\ to site\wwwroot\web
  5. Click the Save button in the Command Bar

waws-virtual-directory

Production Web Site Guidance

In a production environment setting, having an external dependency as part of your deployment process can impede the ability to deploy your application. It is up to you to understand the non-functional requirements of your application which includes the acceptable deployment time. It may be required to ensure that the latest version of your code be available in production in a moments notice. In cases such as these it is important to keep a backup of your dependencies which could either be in your production branch of source control, or maintained independently of your project. It may be necessary to stage your deployment in a staging environment before pushing to a production server. In my next post, I’ll cover how you can deploy to a Windows Azure Web Sites staging slot and swap that staging deployment into production.

Important: Update to Default PHP Runtime on Windows Azure Web Sites

In upcoming weeks Windows Azure Web Sites will update the default PHP version from PHP 5.3 to PHP 5.4. PHP 5.3 will continue to be available as a non-default option. Customers who have not explicitly selected a PHP version for their site and wish the site to continue to run using PHP 5.3 can select this version at any time from the Windows Azure Management Portal, Windows Azure Cross Platform Command Line Tools, or Windows Azure PowerShell Cmdlets. The Windows Azure Web Sites team will also start onboarding PHP 5.5 as an option in the near future.

Explicitly Selecting a PHP version in Windows Azure Web Sites

If you wish to continue to run PHP 5.3 in your Windows Azure Web Site, follow one of the options below to explicitly set the PHP runtime of your site.

Selecting the PHP version from the Windows Azure Management Portal

After logging into the Windows Azure Management Portal, click on the Web Sites navigation item from the left hand menu.

image

Select the Web Site you wish to set the PHP Version for, then Click the arrow to navigate to the details screen.

image

Click on the CONFIGURE tab.

image

Ensure the value selected beside the PHP Version label is 5.3.

image

Perform any action which will require a save that will indicate the PHP 5.3 selection is intentional and not a reflection of the current platform default:

  • Add an App Setting
  • Temporarily toggle to PHP 5.4 or OFF
  • Enable Application or Site Diagnostics
  • Add/Change the Default documents

Click on the Save button in the command bar at the bottom of the portal.

image

Selecting the PHP version from the Windows Azure Cross Platform Command Line Tools

Run the following command from your terminal of choice, be sure that the Windows Azure Cross-Platform CLI Tools are installed and the appropriate subscription is selected.


Selecting the PHP version from the Windows Azure PowerShell Cmdlets

Run the following command from a PowerShell console, be sure that the Windows Azure PowerShell Cmdlets are installed and the appropriate subscription is selected.


Enabling Zend®Guard Extension in Windows Azure Web Sites

Zend®Guard enables you to encode and obfuscate your code to help protect against reverse engineering. It’s understandable that someone would want to help protect their hard work by encoding it, but in order to execute this encoded source on a server it is necessary to enable an extension to decode the source prior to execution.

Getting Started with ZendGuard

Using ZendGuard is out of the scope of this article, as there is plenty of documentation around the process on the Zend Guard User Guide. If you’d like to get the quick overview, watch this video below:

Zend Guard Basics by Zend Documentation

ZendGuard Setup in Web Sites (default runtime)

In order to enable ZendGuard in Windows Azure Web Sites you will need to acquire ZendLoader.dll from the ZendGuard Download page. The remaining steps we will configure php which is built into the Windows Azure Web Sites environment.

Installing a Zend Extension in Windows Azure Web Sites

Now that we have the ZendLoader assembly let’s make sure that it’s loaded into the extensions list in the default php.ini file. We can do this by selecting the configure tab in your Web Site and adding an App Setting.

image

There are a number of reserved App Settings in Windows Azure Web Sites to configure a number of different parts of the default runtime experience, in this particular case we’re going to use PHP_ZendExtensions to load ZendLoader.dll into the default PHP Runtime Zend Extension list.

Ensure you  download the proper ZendLoader.dll for your PHP Version.

As you can see in the image below, the an app setting is created with the key PHP_ZendExtensions and the value bin\ZendLoader.dll, which is a semi-colon delimited list of relative paths in this case the ZendLoader.dll will need to be placed in a bin directory off the root of the Web Site.

You can upload the DLL file via FTP, or download it directly to the bin directory in your Windows Azure Web Site by using KuduExec, which I’ll use to download the .user.ini file later in this article.

image

With the assembly in the PHP pipeline, we still need to do some custom configuration to the php.ini via the .user.ini file. I have created a .user.ini which captures all of the configuration settings available to ZendGuard as well as a command to turn off WinCache file caching which is required in order for ZendGuard to operate.

To demonstrate another feature of Windows Azure Web Sites, let’s use KuduExec to download the .user.ini file into our Windows Azure Web Site using curl.

KuduExec – The Windows Azure Web Sites Command Line

First things first, in order to use KuduExec you need to have it available on your local machine. KuduExec is written in Node.js which you will need installed and configured on your machine. To download KuduExec, use the following command to install it globally on your system.

npm install kuduexec -g

Now let’s look at how to connect to our command line in Windows Azure Web Sites:

kuduexec https://<deployment-user>@<dns-namespace>.scm.azurewebsites.net

Enter your Deployment Password to login to the Windows Azure Web Sites command line. You can download the .user.ini file from a Gist the following curl command:

curl -O https://gist.github.com/SyntaxC4/6084034/raw/cd8e1e27cbaa45db25f94be51968960bf71276bf/.user.ini

Note

Depending on your ZendGuard configuration, you may need to change some of the zend_loader settings.

Exit KuduExec by typing exit.

Refresh the PHP Configuration

By default, PHP is configured to refresh it’s settings from the php.ini file every 300 seconds (5 minutes), you can force this to refresh immediately by doing a Web Site reset.

You can confirm ZendGuard is configured by looking at the following sections of the phpinfo output:

image

image

Deploying your ZendGuard Encoded Application

There are many ways to upload content in Windows Azure Web Sites as described in this list of PHP Tutorials. After ZendGuard encodes the application code, the index.php file in my example looks like this:

image

The actual file is a simple echo of phpinfo()

image

Conclusion

In this example, I demonstrated how to configure ZendGuard with the built in PHP runtime in Windows Azure Web Sites. This will allow you to run your ZendGuard Encoded and Obfuscated code in a highly scalable hosting environment. It is also possible to set up ZendGuard using the Bring Your Own Runtime functionality, which I will explain in a future blog post upon request in the comments below.

PHP 5.5.0 for Windows Released!

php-med-transToday is an exciting day as we welcome the availability of PHP 5.5.0 [Release Announcement]. The team here at Microsoft has been busy preparing PHP 5.5.0 for Windows which has a number of updates which I will cover in this post.

IMPORTANT

With the release of PHP 5.5.0, the PHP Community has also announced that PHP 5.3 will go into “Security Only” maintenance, which will last for a period of 1 Year, at which time PHP 5.3 will enter End of Life (EOL).

What’s New in PHP 5.5.0

The most notable change to PHP 5.5.0 is the inclusion of Opcache extension which is to be bundled into the language. There are a number of other enhancements including:

Language Bundled Opcache Extension

As anyone who develops PHP code knows, an opcode is important to speed up the execution of the script. This is done by caching compiled interpreted PHP code, so that the compiler doesn’t need to be used on each request. If a compiled version of the requested script is cached, the compiler is bypassed and sent directly to the executor. The Opcache extension was contributed by Zend, and is based on their Optimizer+ extension.

Good news for those running PHP on Windows is that Opcache is supported on Windows and performs quite well over the current version of WinCache. You can see some performance numbers below with the new Opcache support in PHP 5.5.0.

Zend contributed Opcache under the PHP LICENSE and the source code is available on GitHub.

What’s New in PHP on Windows

Over the past several years, Microsoft has been heavily investing in PHP on Windows working towards better support for PHP in IIS. In recent years, additional work to ensure that PHP not only work on Windows Azure, but to ensure that PHP is a first class citizen on the platform.

Microsoft Contributors to PHP

Microsoft has two contributors to the PHP project who are within the top 10 committers within the last 12 months. Pierre Joye, one of the two contributors mentioned above, has the most all time contributions to the project with over 6000 commits according to Ohloh.net.

There is a great deal of collaboration between the PHP community and the Microsoft Open Source Technology Center (OSTC) (which is responsible for Q&A and PHP builds for Windows) in order to ensuring extensions are updated amongst other works.

Performance Improvement for PHP on Windows

There have been some major improvements surrounding performance of PHP on Windows. The improvements include moving to the VC11 compiler as well as the new Opcache extension explained above.

Moving PHP Core and Extensions to VC11

There have been a number of improvements which have come out of moving the PHP source and dependencies to be compiled under the latest VC11 compiler. Taking advantage of Profile Guided Optimizations (PGOs) which is a runtime compilation optimization which leverages profile data collected by running performance centric usage scenarios to build an optimized version of an application. You can read more information regarding PGO from the C++ Compiler team blog, I would suggest Profile Guided Optimization: Under the hood and Build faster and high performing native applications using PGO. To better understand how the PHP binaries took advantage of PGO, read Speed up Windows PHP Performance using Profile Guided Optimization (PGO).

Looking at the Numbers…

The team is seeing some significant performance numbers captured in the below tables. The following performance metrics were captured from a machine with the following configuration:

Dell R710
CPU – Intel Quad core @ 2.26Ghz (x2) L5520
Memory – 12GB RAM
HD – 147GB SAS RAID 1
NIC – 1Gbps Intel
Windows Server 2012

Note: Performance metrics are in Transactions per Second (TPS)

PHP Performance on IIS

As you can see, there is a range of 7-15% increase in performance over PHP 5.4 with no caching enabled in IIS against some of the industry leading CMS applications. Opcache significantly increases performance over PHP 5.4 with WinCache, anywhere between 25-152% increase in performance on IIS against the same applications.

PHP-PERF-IIS75

PHP Performance on Apache 2.4

If you are leveraging Apache 2.4 on Windows, you may see an 8-19% increase in performance over PHP 5.4 with no caching enabled. When testing with Opcache enabled over PHP 5.4 with APC caching in Apache, you may see performance gains of between 12-119% on Apache 2.4.

PHP-PERF-APACHE24

Wrapping Up

It’s exciting to see the PHP language continue to grow and evolve as well as the collaboration between the PHP community and Microsoft to continue to advance the support of PHP on Windows and Windows Azure.

Installing CakePHP from the Windows Azure App Gallery

In my previous post Application Frameworks now part of the Windows Azure Web Sites Gallery I introduced the concept of ready to install application frameworks which can be provisioned as part of a new Windows Azure Web Site. The benefits include having a ready to go starting point for building out your application with a tested and fully capable package which includes common Application Settings as well as the proper configuration for IIS.

Today, I’m happy to announce a new addition to the App Frameworks section of the Windows Azure App Gallery, CakePHP. Let’s take a look at the steps to get CakePHP running in Windows Azure Web Sites using the new Gallery item.

Setup CakePHP on Windows Azure Web Sites

To follow along with the example below, sign up for a Windows Azure Free Trial.

In order to provision a Web Site from the Windows Azure App Gallery we must first sign into the Windows Azure Management Portal. Once you’ve logged into the portal you will see the command bar at the bottom of the browse, click New.

drawer-waws-new

This will open the drawer and enable you to select from a variety of different services which you can provision, for this example we’re interested in Web Sites. Select ComputeWeb Sites > Gallery.

drawer-waws-fromgallery

The gallery modal will pop up and allow you to select from a number of well-known open source CMS, Frameworks and other tools.  Select App Frameworks > CakePHP or scroll through the list to find CakePHP.

At the time of writing this article the CakePHP version in the Gallery was 2.3.6.

windowsazure-websites-gallery-appframework

Once CakePHP is selected, click the next arrow at the bottom of the screen to advance to the Configuration page in the wizard.

websites-configure-cakephp

In order to configure a secure deployment of CakePHP, the Cake Foundation suggests including a Security Salt and Cipher Seed. The Web Sites team has conveniently surfaced those settings to the Configuration page, which will get injected into the proper configuration setting in the app/Config/core.php file.

During the configuration, you can select an existing MySQL Database or create a new MySQL Database with your new site. If you needed to create a new MySQL Database, you will receive this screen which will ask for the database name, a region to deploy the database in [Note: It’s a good practice to deploy your database in the same region as your application to reduce latency], you will also need to accept the terms from our partner ClearDB who supplies the MySQL Databases in Windows Azure.

websites-mysql-cakephp-database

That’s it! After clicking the checkmark to complete the wizard your new Web Site will start to provision which includes a configured version of CakePHP which is a great starter point to your next CakePHP Application.

windowsazure-website-site-listing

Once the Status changes to Running, you’re ready to view your new site. You can do this as simply as clicking the BROWSE icon in the Command Bar.

drawer-waws-browse

Congratulations, you have yourself a brand new CakePHP Installation in Windows Azure Web Sites.

WindowsAzure-WebSites-CakePHP

CakePHP is setup, Now what do I do?

Now that the CakePHP Framework is in place it’s time to start building an application. To do so, you’re going to need the source on your local machine.

Download your Web Site files with Git

With Windows Azure Web Sites you can deploy using many source control repositories, this includes Git. However, Git isn’t enabled by default when you create a site from the gallery, so lets find out how to enable Git Deployment (and in our case, a remote repository to clone from).

If you click into the details of your new Web Site in the Windows Azure Portal, you will see a Quick Glance section on the DASHBOARD. Click on Set up deployment from source control to create a new repository in your Windows Azure Web Site.

 

websites-set-up-source-control

Like I said above, there are many options for source control systems, select Local Git Repository then the next arrow to continue.

websites-setup-source-control-git

It may take a few seconds for your repository to be created, so this notification will keep you amused in the meantime.

websites-create-git-repo

Once the repository is created, the portal should redirect to the DEPLOYMENTS tab. Copy the Git URL, you’ll need this to clone your repository on your local machine.

websites-copy-git-url

On your local machine, open Git Bash or your favourite Git command line utility, type the following pasting the git url you copied above in place of <git-url> below, then hit enter.

git clone <git-url>

local-clone-website-repo

You now have a local git repository of your CakePHP Application.

You may have noticed both the Vendor and Plugins directories are missing, this is because they are empty and Git does not track empty folders. Simply create the folder locally and place a file in the directories in order to upload third party code or plugins, respectively.

Download your Web Site files with FTP

To download your Web Site files with FTP you will need your favourite FTP tool, this could be a number of different tools including the command line. Here are the steps you will need to take to configure FTP downloads from your site, I’ll leave the actual downloading up to you.

On the DASHBOARD screen in the portal under the Quick Glance section, you will need to set (or reset, incase you forgot) your deployment credentials. Click on the link which allows you to set the deployment credentials.

websites-setup-deployment-credentials

Fill out the form providing your username, password and confirm password.

websites-set-deployment-credentials

Once you’ve set your credentials, scroll a down the Quick Glance section until you find your FTP or FTPS Host Name.

websites-ftp-links

Notice that your FTP User is a combination of the web site name and the user name provided above, the password is the password which was created when you set your deployment credentials.

Enjoy developing with CakePHP!