http://mark.kolich.mobi/m.php?a=1
But, in the spirit of REST'ful API's I changed the URL pattern to something a little cleaner, and maybe a little more user friendly (easier to remember and recognize):
http://mark.kolich.mobi/m.php/1
Most folks would never even remotely care about this, but I'm somewhat of a perfectionist and maybe even a slight minimalist. So, if this new pattern saves me 2-characters in the URL, then I'm happy. The trick through was updating the PHP that powers my mobile blog so that it gracefully recognizes the old and new style URL. Many search engines and other users have cached links to articles on my mobile blog, so if they use the old style URL, I want to gracefully redirect them to the new one. Here's the PHP that let's me handle both styles, old and new:// The article ID can only contain numbers, so if we get anything else
// use preg_replace() to remove all non-digits.
$a = (isset($_GET['a'])) ? preg_replace("/\D/","",$_GET['a']) : null;
// Check if $_GET['a'] really exists and make sure it's a number
// between 1 and 20. If it doesn't exist, or doesn't meet our criteria,
// then look for an article number in the new style URL. BTW, PHP's intval()
// returns zero (0) if the number couldn't be parsed for whatever reason;
// which works fine for us here.
if(empty($a) || preg_match("/^\d{1,2}+$/",$a)===0 ||
intval($a)<1 || intval($a)>20){
// Try to get the article number from the REQUEST_URI string.
$uri = (isset($_SERVER['REQUEST_URI'])) ? $_SERVER['REQUEST_URI'] : null;
$path = explode("/",$uri,4);
$a = (isset($path[2])) ? preg_replace("/\D/","",$path[2]) : null;
// See if we found anything useful. If not, then bail. Looks like the
// user sent us some junk we don't understand.
if(empty($a) || preg_match("/^\d{1,2}+$/",$a)===0 ||
intval($a)<1 || intval($a)>20){
header("Location: http://mark.kolich.mobi");
return;
}
}
else {
// Tell search engines that the URLS for the mobile
// posts have changed by sending them a 301.
header("HTTP/1.1 301 Moved Permanently");
header("Location: ".$_SERVER['PHP_SELF']."/".$a);
return;
}
// If you get here, the value of $a is loaded
// and validated from *.php/x
If you're feeling adventuresome, and you're running PHP 5.2 or later, you could use PHP's filter_input_array() to validate the input as I described here.
Even so, this works well. If the user visits http://mark.kolich.mobi/m.php?a=1 then I'll redirect them to the new style URL http://mark.kolich.mobi/m.php/1. If the user requests a bogus article, or gives me junk instead of a valid number between 1 and 20, I'll throw them out to http://mark.kolich.mobi.
If you find any problems with this code, please let me know. Enjoy.


Did you find this post helpful, or at least, interesting?