PHP Serving RESTful APIs
Exposing Clean Resource Paths
Problem
You want your URLs to look clean and not include file extensions.
Solution
Use Apache’s mod_rewrite to map the path to your PHP script:
RewriteEngine on
RewriteBase /v1/
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?PATH_INFO=$1 [L,QSA]
Then use $_GET['PATH_INFO'] in place of $_SERVER['PATH_INFO']:
$request = explode('/', $_GET['PATH_INFO']);
Discussion
Use mod_rewrite to expose elegant URLs, such as /v1/books/9781449363758, even when there isn’t a file at that specific path. Without this, you end up with the more clumsy URL of /v1/books.php/9781449363758. If you’re running another web server, such as nginx, use its own syntax for handling this type of URL mapping.
The code in the Solution tells Apache that when it doesn’t find a file or directory at the requested path, it should route it to index.php instead. Additionally, so you can still read in the original URL to properly process the request, extract the path and pass it in as the PATH_INFO query parameter.
Inside your script, parse the path into its components by breaking it apart on “/”:
$request = explode('/', $_GET['PATH_INFO']);
This breaks a request for /v1/books/9781449363758 into:
Array
(
[0] => books
[1] => 9781449363758
)
Now you can take action based on the resource and path
No comments:
Post a Comment