PHP Regular expresssion URL Router

June 23, 2009 No comments yet

In this tutorial we will create a PHP URL router. The developer using the router will be able to define these routes with regular expressions, these will then map to a file, class and method which will be called – very similar to Django’s routing. By using regular expressions to define our URLs we get maximum customizability. /class/method/ based URL routing is too restrictive sometimes. We will assume the user is using an apache or similar web server with mod_rewite enabled. You can adapt this router and use it in your web application or framework.

Quick Note: This is taken straight out of one of my applications. I have a singleton registry object called $core which you’ll see referenced many times. I suggest you make your own or use global variables.

.htaccess

First of all we need to create a .htaccess file in the root directory of your project. We turn the RewriteEngine on, and then declare a rule to route everything except images/js/css through our index.php file. So even if the person goes to www.yoursite.com/directory/file.php , rather than executing that file it will execute our index.php instead.

RewriteEngine on
RewriteRule !\.(js|ico|txt|gif|jpg|png|css)$ index.php

If your building a framework or application…

Light weight alternatives to Apache

June 14, 2009 No comments yet

When it comes to choosing a Linux web server, Apache, as we all know, is almost a de facto standard. There is even a chance that your web host does not even offer (or worse, know of) an alternative web server. So, it’s not a big surprise that many developers don’t know too much about what other alternatives are available to them.