Categories

Request Script

Donate

PHP Routing

Routing in terms of a web application is the selection of content based on the user’s request URI. Typically, routing is very intuitive for PHP, as with most web languages; the user asks for /foo.php and the server executes and serves up /foo.php.

However, an idea I picked up from ASP.NET MVC is their notion of routing. In this way, urls actually look a bit more human-readable, and you can get rid of all the file extensions. Not all the concepts of MVC may translate over to PHP, but the basic idea is to have all requests go first to a routing script which will determine which code to execute from there.

For example, if you had a website which had a forum, you might not want to have the url look like /post.php?postid=12345678. You could instead, make the url /post/12345678/this-is-the-posts-title. This looks a lot better and is very easy to route.

So to set up routing for PHP, first you must get all traffic to get to your routing script. To do this, add the following to your .htaccess file:

# Turn on the RewriteEngine
RewriteEngine On

# Rules
RewriteCond %{REQUEST_FILENAME} !/content/*
RewriteRule .? routing.php

Now let’s analyze each line of the file:

RewriteEngine On

This turns the rewrite engine on in Apache. The mod_rewrite engine needs to be enabled for this to work, but this should come installed and enabled with most PHP installations.

RewriteCond %{REQUEST_FILENAME} !/content/*
RewriteRule .? routing.php

The first line is a condition for rewriting. In the example, I have that the request filename NOT be /content/*. The reason for this is that I do not like static content to need to go through routing. So I would put all images, CSS, and JS somewhere in /content/.

The second line basically just makes all other requests now point to routing.php. This file is the one which will do the routing and which every request will end up going through.

So now let’s take a look at routing.php

session_start(); // if you are using PHP sessions on your site

// put all common included here like connecting to databases, class includes, etc.
// ...

$requestUri = $_SERVER['REQUEST_URI'];

// get rid of query params
$i = strpos($requestUri, '?');
if($i !== false)
{
	$requestUri = substr($requestUri, 0, $i);
}

$urlParts = explode('/', $requestUri);

// do your routing logic here! Here's a trivial example
$script = $urlParts[1] . 'page.php';

// execute routed script
require_once('header.php');
require_once($script);
require_once('footer.php');

The above code should be fairly self explanatory. It assumes that you want your url structure to be /{pageName} mapping to the file /{pageName}/page.php. You can put whatever you want though. Also, the above code puts the header and footer includes in so you don’t need to have them in each of your page scripts (or session_start(), or those common includes you put in the routing script!).

Here is an example of just the routing logic for the forum example earlier:

// ...

// url structure was /post/{postId}/{postTitleEncoded}
if($urlParts[1] == 'post')
{
	$postId = $urlParts[2]; // $postId should be available to the included script file
	// we're ignoring the post title part of the url. It's for human-readability and SEO
	$script = 'post.php';
}
// more routing logic if needed
// ...

// ...

Now post.php can use $postId for its logic. This allows it not to have to worry about the header, footer, or any other common scripts, or sanitizing any input as the routing logic should be able to handle all that.

One immediate concern I had was for performance. I thought about it for a while, and I think there is minimal to no impact on performance, as long as you have that !/content/* exception. If PHP routing is used for anything but PHP files, that’s where the problem would lie. The routing script will probably always be in memory since it’s used for every page call and the implementation of Apache and PHP should (famous last words) be able to handle a single page being hit over and over just as well as several different pages being hit, if not better.

Some people prefer mod_rewrite for handling all of their routing, but sometimes you may need some logic beyond basic string matching. For example, if the user is logged in or has a certain right access, they might be routed to a different page than others. Also, some kinds or basic validation and sanitation can be done in routing that you wouldn’t be able to do in mod_rewrite.

AJAX Form

This script will give a form on a page (or multiple forms) the ability to send off an email once complete. Zero Javascript is required on the implementer’s part, and very minimal edits need to be made to the PHP. Basic validation can be enabled, and this form is resistant to spam bots since it works off AJAX (and thus Javascript, which most bots have disabled). All the different input fields should work (text box, checkbox, drop downs, text areas, password fields, etc) except for file uploads, which I’ll probably handle in a later post.

Example: here
Source: ajaxForm.php

Although the source file is a PHP file, it needs to be included in the HTML as if it were a Javascript as shown in the example.

Note that there are two variables which should be edited by the implementor, both of which are at the very top of the file: $to and $from. These (pretty self-explanitorily) variables are the email addresses which the email is sent to and from. Note that the $to field may contain several email addresses separated by commas. This should be the only edit to the PHP/Javascript code that needs to be made.

In your HTML, add the “ajaxForm” class to your form(s) which you want to use this script. Note that the Javascript will overwrite the “action” property of the form, but this shouldn’t be a concern in most cases.

Two hidden fields should be included, “ajaxFormSubject” and “ajaxFormCompleteDiv”. ajaxFormSubject is the subject which you wish the email to have. ajaxFormCompleteDiv is the id of the HTML element you wish to display (display: block) after the form is successfully complete, like a “thank you” div. Note that if you want the ajaxFormCompleteDiv to be hidden initially, you should hide it with your own CSS. This is for flexibility.

After successful form completion, the form element will automatically be hidden (display: none) and the ajaxFormCompleteDiv automatically shown (display: block).

To enable validation for a field, add the class “required” to the field. The validation only consists of checking if some value was entered.

If a field is found to be invalid, the input, select, or textarea will be given the class “ajaxFormError”. You should add your own CSS to determine the style of this.

This code is meant for designers or developers with little to no programming experience and satisfies this requirement quite nicely as only 2 PHP variables should be modified and the rest is in the HTML.

AJAX Made Easy

While AJAX may seem scary to a novice programmer, all it really does is connect Javascript to a server-side scripting language of choice. In this article, I’ll show how to easily make use of AJAX with PHP.

The notion of AJAX is very simple to understand. Your browser just makes a request to the web server, just like any other request like as if you were navigating to a page, but instead of reload the page and displaying it, it just returns the markup to a specified Javascript function.

Example: Here
JS Source: ajax.js
PHP Source (as text): ajaxHandler.php

Now the example definitely doesn’t make use of best practices for AJAX (I may write a post about that later, but the gist is that you shouldn’t return HTML or “pretty” stuff, but data that needs parsing or even better, a JSON object to be parsed), but it should give you the basics of how to pass data to PHP and then how to get the response back to Javascript. Now anything you’ll want to do, you just need to know how to do it in either Javascript or PHP.

If you take a look into the ajax.js file, there is a class called ajax. Even though AJAX is quite easy, this class exists so that only one call is needed to make and return an AJAX call. While I won’t go through the details of how the function works, to make an AJAX call with this code, just call ajax.call and pass it three things: the URL to request, the parameters to pass, and the callback function.

The URL should be the URL of the PHP (or whatever) code you wish to request. Note that this code uses POST to request the URL. This can fairly easily be changed to GET if needed. The main different between POST and GET is that POST requires two actual requests to be made per request, while GET has a limited size due to URL length restrictions. When sending form data, POST is recommended while when simply requesting data, GET should be used. Here I use POST to cover all bases.

The parameters should be an object with the property names being the parameter name and their values being the value to pass. Passing null is perfectly acceptable if no parameters are needed.

The callback function is a function that the response from PHP (or whatever) will be given to. This function should have one parameter which will be a String containing the response. Note that this function needs to be passed as an object.

Do note that there will be a slight delay from the time you click on the button to the time when the response is displayed. This is because of the latency of making requests over the internet. It is recommended to disabling buttons while the request is unanswered.

Something to note about AJAX is that it is entirely asynchronous. The ajax.call function is non-blocking, meaning that the code that follows will continue to run even before the request comes back. If you are familiar with event driven programming, this should be an easy thing to understand. If not, be cautious with how your code is set up so that it works no matter when the callback happens. Depending on latency and computer speed, the callback could fire immediately after the ajax.call function is called, well after the rest of the Javascript is run, or anywhere in between. Most browsers implement Javascript as single-threaded, but with AJAX it should be treated as multi-threaded and so good practices for shared objects should be used. While there are no locks in Javascript, a careful programmer can make sure the code works as intended.

While the example does absolutely nothing interesting, it should provide the building blocks for creating your own AJAX code for tying your Javascript and PHP knowledge together.