When I sat down to look at PHP again, I wanted to start with a simple router. The idea being that all requests are
forced to the index.php
where the decision is made where to send the traffic.
If it’s been a while since you’ve looked at PHP, or are just starting out, then maybe this will help you out as well.
In the root of your project folder, create an .htaccess
file. This is a “special” file that is used
by most web servers.
1
2
3
4
5
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.+)$ index.php [QSA,L]
Get the requested path with $_SERVER["REQUEST_URI"]
, and require the page you want to display.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<?php
$request = $_SERVER['REQUEST_URI'];
switch ($request) {
case '':
case '/' :
require __DIR__ . '/views/home.php';
break;
case '/contact' :
require __DIR__ . '/views/contact.php';
break;
default:
http_response_code(404);
require __DIR__ . '/views/404.php';
break;
}
?>
Create the /views
folder, and create any view files you need.
1
2
3
// views/home.php
<h1>Homepage</h1>
1
2
3
// views/contact.php
<h1>Contact Us</h1>
1
2
3
// views/404.php
<h1>Error 404</h1>
To test out any of your local PHP files, you can take advantage of the PHP command-line interface (cli) to start a running PHP-capable webserver.
1
php -S 0.0.0.0:3000 index.php
This is assuming of course that you have PHP installed.