Thursday, 9 October 2014

Rewriting URL

When dealing with resful webservice, one of the principle for the architecture is to use "cleaning URL" or the also called Semantic URL  ; one way to do that is to add some rules to redirect URL within an .htaccess file;
Say you have a resource "users",. I could set up a number of URIs like so:
/api/users     when called with GET, lists users
/api/users     when called with POST, creates user record
/api/users/1   when called with GET, shows user record
               when called with PUT, updates user record
               when called with DELETE, deletes user record
To have a correct representation of a RESTful architecture, one can define  an .htaccess file to so that it redirects any of these URIs to one file, 'user.php' :
.htaccess
Options +FollowSymLinks
RewriteEngine On
RewriteRule ^api/([0-9a-zA-Z]+)/([0-9_-]+)$ user.php [L]
user.php
<?php
    $path = $_SERVER['REQUEST_URI'];
    $url_elements = explode('/', $path);
    $verb = $_SERVER['REQUEST_METHOD'];
    echo $verb."<br>";
    echo "ID = ".$url_elements[5]."<br>";
    echo "NAME = ".$url_elements[6]."<br>";;
    
?>

In doing so, while accessing the following URL http://localhost/api/user/12, the screen will print out :

ID = user
NAME = 12