views:

139

answers:

3

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 single PHP-file, and that file takes care of the RESTful-handling and call the right PHP-file.

In example:

  1. The user request http://mysite.com/test
  2. The server sends all requests to rest.php
  3. The rest.php call test.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?

A: 

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.

Josh K
But I want it for all my pages. So I want that mysite.com/test1 goes to my test1.php-file.
Jonas
I don't think you quite understand. If the user requests a file that doesn't exist it will get caught in a redirect loop. That's why you should check to make sure the file exists before redirecting.
Josh K
+2  A: 

Using Apache Mod Rewrite:

Options +FollowSymlinks
RewriteEngine on
RewriteRule ^test$ rest.php [nc]
ImCr
A: 

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;
    }
  }
  ?>
El Yobo