A problem I have often encountered when working with Symfony projects containing multiple applications is the maintenance of the non-production front controllers. These front controllers contain a default check of the client IP address and must be modified to allow requests from any system except localhost (127.0.0.1). The creator of the application is then left to “roll their own” access control in order to facilitate development while still restricting the world at large.

While this is not a problem for Symfony projects which contain a single application, maintenance of these non-production front controllers can quickly become bothersome as the number of applications in the project grows. Any time an allowed address is added or removed all these front controllers need updated manually.

Listing 1 contains a solution to this problem. The source of the front controllers to be restricted gets replaced with this code (with the proper application name, environment, and debug setting of course). It is assumed the same set of IP addresses will have access to all the front controllers which use this code.

Listing 1: web/frontend_dev.php

<?php

if (false !== ($hosts = @file(dirname(__FILE__).'/../config/hosts.allow')))
{
  $hosts = array_map('rtrim', $hosts);

  foreach ($hosts as $host)
  {
    if (substr(@$_SERVER['REMOTE_ADDR'], 0, strlen($host)) == $host)
    {
      require_once(dirname(__FILE__).'/../config/ProjectConfiguration.class.php');

      $configuration = ProjectConfiguration::getApplicationConfiguration('frontend', 'dev', true);
      sfContext::createInstance($configuration)->dispatch();

      exit(0);
    }
  }
}

header('HTTP/1.0 403');
echo '403 Forbidden';

As you can see, the list of allowed addresses is stored in the config/hosts.allow file. This file simply contains an IP address (or partial IP address) to be allowed on each line. A sample hosts.allow file can be found in listing 2.

Listing 2: config/hosts.allow

127.0.0.1
209.85.225.104
192.168.0.
69.147.11.

Problem solved. Now whenever a new IP address or set of addresses needs to be allowed access to your restricted front controllers they simply need added to the hosts.allow file.

It should be noted when matching IP address blocks: since the check uses a substring match on the client address the trailing “.” needs included in the hosts.allow file. Otherwise an allowed address of “69.147.11″ would match “69.147.111″, “69.147.112″, etc.

Happy coding!