Building a Simple URL Routing System in PHP
When developing a PHP application, organising your files and routes efficiently is crucial. A clean URL structure not only improves the user experience but also enhances the SEO of your website. In this tutorial, we'll create a simple routing system in PHP that routes different URLs to different PHP files and handles 404 errors gracefully.
Prerequisites
Basic knowledge of PHP and Apache server configuration.
An Apache server with mod_rewrite enabled.
A basic understanding of .htaccess files.
Directory Structure
First, let's define our directory structure. We'll keep the main index.php
and .htaccess
files in the web root directory and create subdirectories for our pages and authentication scripts.
/webroot
index.php
.htaccess
/pages
home.php
about.php
contact.php
404.php
/auth
login.php
signup.php
Step 1: Configure URL Rewriting with .htaccess
The .htaccess
file is a configuration file used by Apache to enable URL rewriting. This allows us to route all requests through index.php
.
Create or edit the .htaccess
file in your web root directory:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php [QSA,L]
This configuration tells Apache to send all requests to index.php
unless the requested file or directory exists.
Step 2: Create the Routing Logic in index.php
The index.php
file will handle all incoming requests, determine the requested URL, and include the appropriate PHP file based on the URL.
Here's the index.php
code:
<?php
// List of available routes
$routes = [
'' => 'pages/home.php',
'about' => 'pages/about.php',
'contact' => 'pages/contact.php',
'login' => 'auth/login.php',
'signup' => 'auth/signup.php',
];
// Get the request URI and trim any leading/trailing slashes
$request = trim($_SERVER['REQUEST_URI'], '/');
// Remove query string from request
$request = explode('?', $request, 2)[0];
// Check if the requested route exists in the routes array
if (array_key_exists($request, $routes)) {
// Include the corresponding page
include $routes[$request];
} else {
// Include the 404 page
include 'pages/404.php';
}
?>
Step 3: Create the Page Files
Next, we'll create the individual page files. These are simple PHP files that will be included based on the requested URL.
pages/home.php
:
<h1>Home Page</h1>
<p>Welcome to the Home Page!</p>
pages/about.php
:
<h1>About Page</h1>
<p>Welcome to the About Page!</p>
pages/contact.php
:
<h1>Contact Page</h1>
<p>Welcome to the Contact Page!</p>
auth/login.php
:
<h1>Login Page</h1>
<form action="process_login.php" method="post">
<input type="text" name="username" placeholder="Username" required>
<input type="password" name="password" placeholder="Password" required>
<button type="submit">Login</button>
</form>
auth/signup.php
:
<h1>Signup Page</h1>
<form action="process_signup.php" method="post">
<input type="text" name="username" placeholder="Username" required>
<input type="email" name="email" placeholder="Email" required>
<input type="password" name="password" placeholder="Password" required>
<button type="submit">Signup</button>
</form>
pages/404.php
:
<h1>404 Page Not Found</h1>
<p>Sorry, the page you are looking for does not exist.</p>
Explanation
Directory Structure: We organized the main
index.php
and.htaccess
in the webroot directory, with individual page files in apages
directory and authentication files in anauth
directory..htaccess
File:RewriteEngine On
: Enables the rewrite engine.RewriteCond %{REQUEST_FILENAME} !-f
: Checks if the requested filename is not a file.RewriteCond %{REQUEST_FILENAME} !-d
: Checks if the requested filename is not a directory.RewriteRule ^(.*)$ index.php [QSA,L]
: Rewrites all requests toindex.php
.
index.php
File:Defines available routes in the
$routes
array, mapping paths to their respective files.Parses the request URI to get the route.
Includes the corresponding page file if the route exists in the
$routes
array.Includes a
404.php
page if the route does not exist.
Conclusion
By following these steps, you can create a simple yet effective URL routing system in PHP. This setup allows you to organize your files neatly and handle different URLs efficiently, improving the user experience and maintaining a clean codebase.