How can I quickly set up a RESTful site using PHP without a Framework?
I would like to quickly set up a RESTful site using PHP without learning a PHP Framework. I would like to use a single .htaccess
-file in Apache or a single rule using Nginx, so I easyli can change web server without changing my code.
So I want to direct all requests to a开发者_如何学C single PHP-file, and that file takes care of the RESTful-handling and call the right PHP-file.
In example:
- The user request http://mysite.com/test
- The server sends all requests to
rest.php
- The
rest.php
calltest.php
(maybe with a querystring).
If this can be done, is there a free PHP-script that works like my rest.php
? or how can I do this PHP-script?
Using Apache Mod Rewrite:
Options +FollowSymlinks
RewriteEngine on
RewriteRule ^test$ rest.php [nc]
Yes, make a 404 Redirect
to a page called rest.php
. Use $url = $_SERVER['REQUEST_URI'];
to examine the url. In rest.php
you can redirect to wherever you want.
This only requires one rule (404
in your .htaccess
file).
You have to be careful and make sure that if the page requested (e.g. mysite.com/test1 doesn't have a test1.php) errors out with a 404 you don't get yourself caught in a loop.
Modified slightly from the way that Drupal does it. This redirects everything to rest.php and puts the original requested URL into $_GET['q'] for you do take the appropriate action on. You can put this in the apache config, or in your .htaccess. Make sure mod_rewrite is enabled.
RewriteEngine on
RewriteCond %{REQUEST_URI} !=/favicon.ico
RewriteRule ^(.*)$ rest.php?q=$1 [L,QSA]
If all you then want to do is include the requested file, you can do something like this
<?php
if (!empty($_GET['q'])) {
$source = $_GET['q'] . '.php';
if (is_file($source)) {
include $source;
} else {
echo "Source missing.";
}
}
?>
You really don't want to do that, however; if someone were to request '/../../../etc/passwd', for example, you might end up serving up something you don't want to.
Something more like this is safer, I suppose.
<?php
if (!empty($_GET['q'])) {
$request = $_GET['q'];
switch ($request) {
case 'test1':
include 'test1.php';
break;
default:
echo 'Unrecognised request.';
break;
}
}
?>
精彩评论