Ollie Ollie - 7 months ago 42
PHP Question

Converting a very simple htaccess into a PHP router?

I'm hoping I can get some help with a relatively simple problem:

I've been programming a PHP application for university and thanks to a complete lack of forethought by me, the servers they are testing our apps on aren't Apache, they are just the

php -S
servers (PHP built-in server).

So my app relies completely on routing of URIs to one specific file, something I had working well in
.htaccess
:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ api.1.0.php [L,QSA]


I am aware that you can use router files when using the normal PHP servers, but could anyone help me 'convert' this
.htaccess
file into a PHP router?

Thanks in advance to anyone who can point me in the right direction!

EDIT: I guess a better way of putting this question would be, can anyone help me understand what the
.htaccess
file is doing? And then I could convert it into PHP fairly easily.

Answer

This is easy. Use this way router.php:

<?php
    $path = parse_url($_SERVER["REQUEST_URI"], PHP_URL_PATH);
    if (!file_exists($path))
      include "api.1.0.php";
    else
      return false;
?>

The above code is a replacement of the .htaccess file you have:

RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ api.1.0.php [L,QSA]

I guess a better way of putting this question would be, can anyone help me understand what the .htaccess file is doing?

  1. RewriteEngine On - Start the Apache2 Rewrite Engine module.
  2. RewriteCond %{REQUEST_FILENAME} !-f - When the file doesn't exist on the path,
  3. RewriteCond %{REQUEST_FILENAME} !-d - When the directory doesn't exist on the path,
  4. RewriteRule ^(.*)$ api.1.0.php [L,QSA] - Whatever you give, serve it to the api.1.0.php with the query string, and stop the rewrite rule here.

This code works for this way:

php -S localhost:80 router.php
Comments