PHP: We are getting slow and sluggish, and we’re lazy and arrogant about it.

In my most recent blog, I wrote about how I feel that too much of the world’s logic is coming onto the shoulders of PHP, these days. Today, I’m will be showing you why and how PHP’s powers could be harnessed better and more. We, as PHP web developers, should be absolutely fully aware that we’re allowing insane amounts of processing power to do too much work when it’s absolutely unnecessary to do so dynamically.

Say what now?

Here’s part of the problem: PHP developers usually don’t really know the difference between what’s static and what’s not. Simply put: there is only one variable. The request. Anything else should be as static as possible. If I would introduce a configuration file with loads of variables, a typical C programmer would argue: “Those are build parameters. They don’t change unless your environment changes, so they are static and should be handled by a preprocessor and macros. You don’t need continuous evaluation of static data”. A typical Java programmer would probably put stuff like that in a static final constant property somewhere, knowing (or assuming) that the compiler will optimize and inline usage of these settings 1.

PHP doesn’t do either. We have no preprocessor, and we have no compiler optimizations on that level. Mainly, because PHP originally was a platform that was supposed to do some simple processing and spew out some dynamic content, as fast as possible. But the PHP community is growing up. We want real OO programming, we use design patterns, we think about dependencies, maintainability, scalability. Stuff that grown-ups do.

But then, what the hell is wrong with this picture?!

I was having performance trouble with one of my Symfony projects at work. So I decided to do some performance testing. Please note that I absolutely love Symfony. There is no framework out there that will actually help you design your application better, and it brought me and many of my colleagues more joy in life. Really. Please understand that this isn’t really about Symfony, because I am pretty sure most of it goes for any other current-generation framework.

I set up some benchmarking comparisons. This isn’t scientific evidence, to be frank. This is experimental science. I was having a hunch, and this indicates that my hunch was correct. So here goes.

The example controller in the Symfony standard edition

Whenever you start a Symfony project, you would typically bootstrap from the standard edition, remove the demo code and add your own bundle. The example controller does something pretty simple. It responds to a URL /hello/..., where the dots may contain anything but a forward slash. Here’s the code:

<?php
 
class DefaultController extends Controller
{
    /**
     * @Route("/hello/{name}")
     * @Template()
     */
    public function indexAction($name)
    {
        return array('name' => $name);
    }
}

The idea is simple. /hello/{name} routes to this controller, the controller returns an array of named variables, and the @Template annotation makes sure the template corresponding to the controller is rendered. This is usually a twig template, and in this case, the template looks like this:

Hello {{ name }}!

Not just to be a pain in the ass…

How would you have done this 15 years ago? Probably something like this. Create a PHP file in hello/index.php containing:

Hello <?= htmlspecialchars($_GET['name']) ?>!

and a .htaccess in the web root containing:

RewriteEngine On

RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule hello/([^/]+) hello/index.php?name=$1 [L]

Right? It doesn’t really do anything more than that. And if I’m absolutely honest about it, useless as the example may be, it shouldn’t be done any other way.

So, just for the sake of curiosity, lets see what a difference in performance this is. I set up two identically configured hosts on my local machine in Apache, but with different webroots, just to be as close as possible to a regular development environment I normally use. The first web root is the regular web/ directory from Symfony (and I renamed it to web-1). The second is another directory containing the setup as described above.

With ‘ab’ (Apache Benchmark), you can get a pretty good idea of performance increases if you’re optimizing your website, one way or another. You can basically pass in an URL and have multiple concurrent users hammer that URL for a specified number of times. So that’s what I did. I usually start with 1000 requests, with 20 concurrent users. This usually gives a good comparable impression of speed.

First off, the dev, debugging version of the symfony app. Of course, you wouldn’t normally test performance in a development or debugging environment, but it’s here for the sake of comparison. Here’s the most relevant2 results of ‘ab’.

Concurrency Level:      20                    
Time taken for tests:   25.058 seconds        
Complete requests:      1000                  
Requests per second:    39.91 [#/sec] (mean)

Second, the prod, non-debugging version of the symfony app.

Concurrency Level:      20
Time taken for tests:   5.302 seconds
Complete requests:      1000
Requests per second:    188.61 [#/sec] (mean)

That seems pretty decent. Just under 200 requests per second were managed. Let’s increase concurrency to see what happens:

Concurrency Level:      250
Time taken for tests:   7.153 seconds
Complete requests:      1000
Requests per second:    139.80 [#/sec] (mean)

A slight drop in performance was to be expected, but it is at least pretty steady and stable.

Now let see how the 1998 version of the same “application” would perform.

Concurrency Level:      20
Time taken for tests:   0.178 seconds
Complete requests:      1000
Requests per second:    5614.76 [#/sec] (mean)

Wait. What? Over 5500 requests handled each second? That means a performance increase of 30. Not 30%, a FACTOR of 30. Nearly 30 times faster. The last time I saw numbers like these were when I ran benchmarks on a Varnish cache….

This would mean that if I were to run the same test with 30 times as much requests, the 1998 version should manage equally:

Concurrency Level:      20
Time taken for tests:   4.482 seconds
Complete requests:      30000
Requests per second:    6693.93 [#/sec] (mean)

At these numbers, the measurements apparently show even better results! And if we would increase concurrency, it would at least have the same relative performance as the other one:

Concurrency Level:      250
Time taken for tests:   6.366 seconds
Complete requests:      30000
Requests per second:    4712.83 [#/sec] (mean)

Let’s look at this for a few seconds. Just to be sure we understand what this means. This means the stripped version of the functionality runs roughly a factor 30 faster than the one implemented using the framework, both with 20 and 250 concurrent users.

But if these numbers are possible, why then, why do we think all the framework’s benefits outweigh these mind-boggling disadvantages?

The counter-arguments

You have no request listeners and therefore no security, no logging, etc, etc…

I know. And you are right. I don’t. But none of those are needed in this example. And that’s exactly what’s wrong with our mindset. We load tons of utilities and tons of logic to requests of which in 80% of the cases, only 20% actually need, and we keep on saying that the ease of use and the well-thought design are good arguments to have such a horrendous performance impact.

Be honest. If you would buy a new server, would you rather have it installed bare bone without any software on it so you can carefully pick your stuff, or would you have the entire Ubuntu Software center installed, so you can use it whenever you can?

Sure, there is a middle road, but lets find a middle road that is the best, not the one that is the most convenient just for us developers.

But you can cache it!

There is only one right answer to such a suggestion. Caching sucks3. Yes, I know, caching is cool, because it can make stuff insanely fast (try Varnish one time. Unsavory goo will drip from your lips, I promise you). But that’s not the point, really. Caching complicates stuff. Complications are just like expensive toys. 1) You don’t really need them, 2) they make you worry about breaking things that shouldn’t really matter and 3) you already have enough of them.

So we should install php3 again and get rid of the frameworks?

Balls, no! This is something the people behind the frameworks should be aware of. But at the very least, the people using them should be aware of it. Don’t tell your project manager (or worse, your client) that the performance is okay, and that you just need a few days R&D to implement caching, just tell them the framework is relatively slow but that you think the extra cost in hardware and complexity of caching mechanisms outweigh the design and maintainability benefits. And be very careful to really mean it and know what you’re talking about.

Code generation is paramount to performance!

I’m not the type of guy to point out problems and not think of solutions beforehand. I have been thinking about this for quite some time, and thought of building something myself. But the fact of the matter is: I don’t have the time nor the persuasive character to actually get it done.

What would be needed is a build system that “folds out” into smaller pieces of somewhat repetitive PHP. We write the development code just like we did before, but when deploying to a non-development environment, all the bits and pieces should be as static as possible. Anything that is dynamic but could, in theory, be static, must be factored out. This means, in case of Symfony, that

  • It is a bad practice (or even unsupported) to have dynamics inside your Bundle classes. Use the service container for this. This way, the bundles needn’t be loaded nor initialized on each request;
  • The service container and accompanying files should be loaded lazily. This can be achieved using require_once calls whenever necessary. The compiled code should do the same.
  • Service container and compiled DI code (we have this already, but could even be more effective) compiles into separate files in stead of a big class that gets loaded everytime.
  • Configuration must be compiled statically
  • Templating must be optimized such that it generates the most efficient PHP code possible. Using magic like the detection of ‘getters’ and such should be removed. May be even consider it a bad practice to use objects in templates at all.
  • Routing must be done statically. Dynamic routing is runtime logic and can be done inside the controllers.
  • Request listener code is compiled into the controller files, so templating listeners, error handling and security are as efficient as possible.
  • Resolution of bundle aliases is done at compile time
  • Handling sub requests is done by simple includes

And on goes the list.

And now, for some action

I have built a little “proof of concept” that shows you the idea. I wrote the resulting code by hand, but with most of the logic already in place, a compiler with some optimization passes in the resulting AST could do anything that i did by hand automatically.

Here’s the performance impact difference:

The ‘hello {name}‘ example:

Standard Symfony Optimized version
188 rps 1640 rps

An example using doctrine

Standard Symfony Optimized, with entire service container Optimized, only doctrine service
~135 rps ~320 rps ~350 rps

In the second example, (which is configured at route db/{name}), the entire service container is loaded, by including the appProdProjectContainer from the cache. In the last example, routed through db-optim/{name}, the doctrine service and it’s dependencies are loaded by including files with their service definition. This adds another ~10% increase in performance, which is still worth considering, imho.

Note that the doctrine services only use per-request caching (ArrayCache), in this example.

What’s the catch?

The catch is, most of the overhead from Symfony’s kernel is from the request listeners. There are a whopping 15 (fifteen) services that listen to every request in Symfony. All of these listeners can be optimized into pieces of code which are included in the controller files, where the “listening logic” (i.e., checking if the listener should do anything) can be done by a static line of code. In the examples above, you can see this happening for the templating listener, which is only checking if the return value of the controller is an array. The fact that it’s in place right there, can be controlled by the @Template annotation. The same would fly for @Secure and @Route annotations. Some listeners contain global static logic (such as the locale listener) or are generic, but nonetheless static (such as exception listeners.

With the Kernel structure as it is now, there is no way to have these listeners come into play only when needed. They are initialized every request, and therefore all dependencies that these listeners may have, are initialized. There is only one way to get around this. Compile all initialization into the controller files, but guarded within the conditions these listeners should provide. Just like the is_array() example for the logic of the Templating listener, this can be done for any other listener.

The sharp reader must have noticed that I disabled all listener logic in my example. This is the reason.

To conclude

I have posted before about a paradigm shift towards declarative programming. I am also arguing that this shift should include a better sense of balance between performance and maintainability. PHP’s road to success was paved by performance. If we lose that, there is not much reason left not to choose other platforms.

A final disclaimer: I am not bashing. I hope that this will lead to more good in the PHP community. At the very least, I dropped my thoughts and can leave it simmering for now. If you read the post entirely, thanks for your patience.


  1. I’m not sure if the Java compiler works this way, but I’m just assuming that it does some kind of optimization for constant values. 

  2. I am using the following command line to do these tests: ab -n 1000 -c 20 http://the/url/ | egrep '^(Time taken|Concur|Requests per|Complete)'. The regular output of ab holds a lot more statistical information. I am performing these tests locally, so they vary a lot; I have of course some other programs running which interfere with the performance. I am aware of that. The numbers don’t really matter that much, but the relative differences do. 

  3. Cache invalidation is one of the two hard things in computer science. The other one is naming things and off-by-one errors. 

Posted in Development | Tagged , | 1 Comment

PHP in the web development world: are we doing it all wrong?

Some thoughts and ponderings on how “the frameworks out there” might not do it just as right as they should.

The UNIX principle applied?

Something that is currently overlooked in a large part of the PHP community is that not all design patterns are necessarily implemented in PHP code. Your webserver can be considered the front controller of your application too. Routes can be defined using your filesystem and webserver configuration. Not everything has to be Object Oriented to be well organised and well structured. To gain perspective, here are some ideas to think outside the box, and not have OO patterns drive you beyond reason.

Some perfectly good solutions to, for example, caching and distributed processing, are commonly overlooked because of the simple presumption that everything should be done inside PHP or should at least be controlled by PHP. In my opinion, this might be a symptom of the Not Invented Here syndrome, and is thus by definition something to be questioned. It makes modular reimplementation in a different platform or language virtually impossible, which troubles long term development of web applications. You can not and must not feel confident that anything you want can or should be done in PHP. The language is irrelevant, the platform is irrelevant, the choice for PHP should be one based on those aspects that make PHP a better choice than another platform or language. If the outcome is PHP, use it. If it is not, it should be of least possible impact on the design choices you make for the rest of your application.

Why is the question important?

We need to be more and more prepared for distributed and parallel processing, which means we need to slice applications down to small and simple bits to be processed on any CPU or filesystem. That means that, while employing nice OO implementations of design patterns inside frameworks like Zend Framework, Symfony and the likes1, we are in fact building monolithical applications, that can be called and routed only through a single front controller file (usually index.php), which doesn’t make the design of the application internals monolithic per se, but does make the application an sich monolithic.

Continuing with this type of development is in huge conflict with various philosophies, such as the UNIX principle. We build one application that does a lot of things very well2. This UNIX principle is not something to be overlooked lightly, because it is historically the single greatest success factor of free software and UNIX based development such as Linux, BSD, GNU, etc…, not to mention PHP. Note that free software means “Free to choose what software you want to use” also; not only free in terms of money or legalities, but also free in terms of dependency and freedom of choice.

Moreover, note that the UNIX philosophy holds strong resemblance to the Principle of Least Knowledge and Separation of Concern, which, in my opinion, are by far the two most vital and important fundementals of software design, when keeping maintainability, testability and long term development in mind. Parts of the application that need updating because either the code is irrelevant or some better component has arisen, should be easily cut out and replaced by another. Think of, for example, replacing Apache with NginX, or even replacing the current PHP payment module with a Java one.

Any component in an application should be responsible for one thing in the application, and one thing only. Vice versa, the component that does the job, should be the component that is the very best at that job. You wouldn’t write your own SQL implementation, if you know there’s perfectly good relational databases out there. So why build your own page caching mechanism if the webserver can cache pages for you? Why build your own routing and dispatching system if the webserver has perfectly good routing and dispatching systems in place?

What with those quote MVC unquote frameworks?

PHP does one thing very well: it is a very fast interpreter of a reasonably simple programming language, and is best suited for processing variables (typically CGI requests) and responding with text output (typically HTML formatted content), while communicating with any backend such as MySQL and filesystems.

MVC frameworks are deviating from this premiss. They hold the PHP application responsible for far more than just handling an incoming request and serving the response. This could be a problem. It complicates the application design very much that all those responsibilities come onto the shoulders of a single application. The danger lies in the fact that inside this application, there might be more trouble identifying the responsibilities and concerns of the different components. If you would separate those responsibilities from the main application, you would find that there is a lot that we’re dealing with inside our application, which is very irrelevant to the application’s own concern.

The best example of this is caching. Either caching stuff that is coming from the database (which a properly configured MySQL already does for you), or caching entire pages (which can be done by the web server): this does not necessarily belong in your PHP code. It belongs in your application, yes, but your application consists of more than just PHP. It is the entire stack of software that all follow the UNIX principle: Linux, Apache, PHP and MySQL. Of course, substitute any of the software with an equivalent alternative, if you have reason.

Another example is routing and dispatching. One of the most tedious and tiresome jobs inside your application is making sure that every link is SEO friendly; i.e. that it contains words that are relevant to the page’s content, and that it’s hierarchical position is relevant to where the page belongs in the site, while still having an idea of what the canonical url of that page should be to avoid duplicated indexing by search engines. I have had not a single project where this would cost not a few hours – at best – to take into account. Why? Because we think to hard about it, and we fear the simple solution might impact performance.

Where complexity is, is where the problem lies

Whenever you find you’re adding complexity to your application because of non-functional requirements such as performance reasons or cost reduction, you need to take a step back and re-evaluate the problem at hand.

A very simple example of this is a YAML file read by a set of PHP classes, rendering a PHP array. This array can be cached in a compiled form using var_export. Having the application itself responsible for this compilation will add complexity to the set of responsibilities of the application. It would be much easier to have the application depend on a PHP configuration file, and let some build process make sure the YML file is compiled into PHP.

Another example is compilation of template files. If you have a set of template files in another language than PHP, for example Twig or Smarty, you can have the compilation of these files be part of a build process. This doesn’t have to be on-the-fly. PHP programmers are used to having stuff work “on the fly”, but it is a convenience that can bite you in the ass. It’s far easier to have a build script that makes sure all cachable data is flushed, than have your application responsible for checking of freshness of these caches. To be even more exact: your application doesn’t even need to know that the stuff it’s reading is actually a cache. It only needs some files, and they’re there.

My final example is SEO friendly URL’s. There is no reason the application itself should worry about this. We have lots of available tools to rewrite outbound and inbound url’s to whatever we need to rewrite. The only thing this tool needs to know is a very simple “from” => “to” mapping of all these URL’s, and that’s it. The program can translate friendly URL’s into internal URL’s, and vice versa. If the program does that, and does that very well, we are out of the pickle.

Data versus layout

Formatting the data of your application in to whatever format (usually HTML), is the responsibility of some sort of view renderer. Action Controllers have the responsibility in translating a request into some sort of response, and usually dispatch to a view renderer internally to have the response formatted as HTML. Now here’s something fishy going on. The action controllers gain three responsibilities in this way; two explicit (handling the request with the appropriate action and returning it’s result) and one implicit: rendering the result. Since the result of any action always is data, the action controller should not be responsible for the formatting of the data. It is in fact irrelevant at that point in time. You’ll just want to know what the result of that action is; either some state (success or failure) or some data. It makes much more sense to have an intermediate format for this (be it a PHP array of data, XML, JSON, or some other form), and have the view on this data or result be detached entirely from the action’s operation. This way, the action controller has only one responsibility: returning the request’s result. Note that the request can be defined as simply as a few method parameters; it needn’t be an HTTP request as such.

The front controller of the application can be responsible for dispatching one front request to one or more action requests, that all have their result. Whether or not the front controller renders this response as HTML is moot.

Why not utilize PHP as a build result?

I think we all might gain more in using PHP as a result of our project’s build. We might simply program in a higher level programming language, and have some compilation or build process build all kinds of php files, that may contain a meriad of repetitive code, just because that is what ultimately the PHP interpreter is best at. Simply preprocessing the hypertext, in stead of doing it the other way around and having PHP implement byte code caches and high level programming features. Maybe PHP was the right language right before it got cocky…


  1. Which I am, of course, a great supporter of. Design inside the code is never something to be taken lightly. 

  2. Let’s at least assume that the end result is in fact an application that does the things it does well ;)  

Posted in Development | Tagged , , , | Leave a comment

Tetris in HTML and Javascript

First, I saw the documentary Ecstacy of Order. Then I thought of great things, like building 3D Tetris in HTML5 canvas. I started it, just typing away, of course only Vanilla JS. But after a few hours, having the simple Tetris basics covered, I got bored and stopped.

But wait, there’s still hope! I thought I could write a post about me thinking of awesome stuff, getting the basics working and then never finishing it. So I started typing this post, but halfway through, I decided that the basics are good enough. And that the basics are worth posting too.

Sorry if I disappointed you. Have fun reading the code ;) The gameplay is not that interesting.


  1. The controls are A & Z for rotating, < and > for moving. You can also use your cursor keys if you use Firefox. Didn’t test it in IE, btw. 

Posted in Development | Tagged , | Leave a comment

Symfony2: A two piece puzzle.

If you’re getting started with Symfony2, you’ll get something running pretty quickly. The AcmeBundle contains some of the basic features you’ll need when writing a Symfony2 app. The basics lie in the MVC paradigm, so there is some model (Doctrine ORM), some view (Twig templates) and some controllers.

However, none of that is the real core of Symfony2. The most interesting part lies in two main components of the framework. First, the HttpFoundation component and second, the Service container.

The HTTP Kernel

Ordinarily, with any controller framework out there, you’ll have a front controller, a router, a dispatcher and some action controllers that work together to generate output for any URL that is requested within your app. In essence, this is no different in Symfony2. There is something extra though. The HttpKernel, which is actually the core of your application is responsible for speaking HTTP. The developers of Symfony2 have put extra effort into nitpicking every aspect of the protocol, such as caching, so that any application written with the HTTP Component would have all the tools at hand to harness the power of HTTP.

The request loop

So, what actually happens when a typical Symfony2 app handles a request, is that a Request object is forged from all PHP’s relevant variables, it is dispatched into the Kernel as an event. The kernel holds a reference to the service container too. Each of the services registered as an event listener for this particular event is notified, so they can build a response. Then the response triggers a new event so all listeners can influence the response again, and ultimately the Response object is sent to the client.

Both the Request and Response objects reflect HTTP messages. As you probably know, any HTTP message is made up from a status line, a set of headers and an optional body. The headers contain protocol information and the body contains content. Usually, when you visit a page, a GET message is issued to the server, containing some headers on how your browser is configured and what host we want to get the URL from. The webserver responds with an answer, containing a status line which indicates the nature of the rest of the response, headers about the size of the response and some other useful information such as how long the resource may be cached by proxies and browsers, and, finally, a body, usually containing the resource data of the requested object if the request succeeded.

Parlez-vous HTTP?

In ye olden days, it was typical for a PHP script to always execute the exact same way, no matter how the user configured their browser or what information on caching was available. Moreover, it was common to have PHP scripts always send, what we affectionately called the “no cache headers”, which instructed the browser to absolutely never cache the page and please always come back to refresh the data, so all data was up to date for all PHP pages and all visitors, always. This had also to do with a particular browser that tended to cache more than was actually instructed by the web server, and customers who wanted to see changes rather sooner than later. Well, the conclusion was, that we, as a profession, never learned to parler HTTP.

Nowadays, with applications getting bigger and application speed, performance and stability are makers or breakers of the application’s success, you’re soon too late to dive in. There was a few years where we could get away with caching only in the backend by optimizing MySQL’s query cache, utilizing simple file caching mechanisms or firing up APC, Memcached and all the likes. All very useful, but only half the story.

Get up `ahhhh! Like a cache-machine

Basically, there are two ways of caching stuff. You can tell the client to keep a resource a maximum amount of time, or you can tell them when the resource was last modified 1. These two models are called Expiration and Validation, respectively.

In the first case, a client may keep the data as long as is specified. In the second case, the client must check back with the server to see if their cached version of the resource is still valid. If not, the response proceeds as usual; if so, the response is set to a 304 Not Modified status and is returned without a body. Expiration and validation can be combined so the client is told how old a resource is and with what frequency they should check back to validate the resource. That’s the short version. Read the longer version here.

The service container

The service container is a registry. What’s a registry, you say? It is a container object that contains immutable objects based on unique keys (much like a “hash” or a “map” structure), which is application wide. Martin Fowler describes it as “A well-known object that other objects can use to find common objects and services”2. The service container itself, therefore, is not that big a deal. THe idea behind it, though, is that all the services that are available in the service container can be loaded on demand. This phenomenon is called lazy loading or bootstrapping. That means that if you have a gazillion services defined, and not one of the lot is used, none of them will be instantiated. This means that if you have a PHP script cropping an image on-the-fly, that does not need the database connection will not open the database connection, even if the script uses the same front controller logic. Now, that sounds like it could be useful.

Depend this!

The clever thing about Symfony2′s service container is that it ships with a load of logic to resolve and inject dependencies. What that means is that if you have, say, a model class which depends on a database connection, you only have to explain to the container how the dependencies can be instantiated and how they reference each other, and the service container will know how to resolve the dependencies. This sounds like a lot of overhead, but as this dependency resolution is done at compile time, and PHP code is generated that actually has all such depencies resolved already, there really is next to none.

And then?

Get on the Symfony2-wave. It is rolling like crazy and Github is exploding with bundles (symfony2′s modules) and contributors. If you know the Kernel and the Dependency Injection components, you should head over to the Form component. Then you know about everything you need to know to build a real Symfony Bundle. The rest will come as you go.

One last tip, don’t use the Bundle Generator if you don’t know what it generates and whether you need it or not. Just create your bundle by hand, you can always start generating bundles if you actually know what it does. My next post on this topic will be a simple guide to help set things up by hand in stead of all the command line wizardry. Why? Because then you actually know what the wizard conjures.


  1. There is also something called “E-tags”. In effect, this is the same as a Last-Modified. The semantical difference is that an E-Tag should represent a state of a resource (e.g. a hash, which would of course change as the resource changes) and the Last-Modified always represents a date. The (in)validation works exactly the same. 

  2. http://martinfowler.com/eaaCatalog/registry.html 

Posted in Development | Tagged , , | Leave a comment

Using a .pfx to install an SSL certificate

Got a .pfx file and need to install an SSL certificate with this? Here’s how I did it. You’ll need to extract the signed public certificate (public key) and the private key without passphrase.

cd /etc/nginx/
mkdir ssl
cd ssl
mv /path/to/pfx/file.pfx .
chmod 400 file.fpx

First extract the public certificate. You might be asked for a password.

openssl pkcs12 -in ./file.pfx -clcerts -nokeys -out public.crt

And extract the private key:

openssl pkcs12 -in ./file.pfx -nocerts -nodes -out private.rsa

Now you can test the server on an arbitrary port, using openssl:

openssl s_server -www -accept 443 -cert ./public.crt -key ./private.rsa

Make sure no one can read the files other than you:

chmod 400 /etc/nginx/ssl/*

With NginX it is now easy to fire up the server. I used a proxy for this, because from an architecture perspective, this is the easiest:

server {
    server_name example.org;

    listen 443 ssl;
    ssl_certificate /etc/nginx/ssl/public.crt;
    ssl_certificate_key /etc/nginx/ssl/private.key;

    location / {
        proxy_pass http://example.org/;
        proxy_set_header Host $host;
        proxy_set_header X-Ssl on;
    }
}

I pass an additional X-Ssl header to the backend so they know we’re publicly serving through the SSL proxy (e.g. for building absolute URL’s). Once you actually know how to do it, it is easy as pie.

With thanks to Yadab Das and Berk D. Demir

Posted in Linux & BSD | Tagged , , | Leave a comment

PHPUnit: Closures as dataProviders help with repetitive code

Since PHP5.3 we have closures. The concept behind closures is unbelievably powerful, and even though PHP has struggled with the concept of typing, callables and whatnot, the main concept of closures remains: passing logic in stead of data, or even: as if it were data. In my previous post I argued that functional and declarative programming will prevail over pure OO on the long run. This post proves another example of why.

Read More »

Posted in Development | Tagged , | Leave a comment

Declarative is the new black.

The paradigm shift in the purest sense of the expression. The old paradigm makes way for new ones. And declarative is the new one. Well…, not new newRead More »

Posted in Development | Tagged , | Leave a comment

Symfony2 + PHPCR + Doctrine2 + Jackalope recipe

Lately I’ve followed some developments in the Symfony2 corner of the PHP community with great interest. One of the most enticing developments is the usage of a Content Repository as a backend for your CMS. There is some work being done on the Symfony CMF, combining Symfony2, Doctrine2, PHPCR and Jackalope into a set of tools for building CMS’es based on a Content Repository backend. I didn’t get anything of the CMF to run yet, so I decided to dive in to tying these separate techniques together myself, and get a little proof-of-concept working. Here’s the code, and here’s the recipe: Read More »

Posted in Development | Tagged , , , | 11 Comments

Failure in a bash script usually means failure of the script

So, when you write a bash script that does a certain amount of tasks for you, but you don’t want the script to keep running after some command inside the script failed, simply add a line to the script. Read More »

Posted in Linux & BSD | Tagged , | 1 Comment

Apply low priority to low priority processes

My transmission client was hogging my machine. Then I realized I never really use process priorities for CPU and/or IO, which is actually a pretty bad thing, considering some processes just are there to get some job done, but don’t need priority at all. Then I realized I also never use it for backup and such, which could be a problem for the server I’m running the backup on. Read More »

Posted in Linux & BSD | Tagged , | Leave a comment