PHP code example of dspaccapeli / file-based-router
1. Go to this page and download the library: Download dspaccapeli/file-based-router library. Choose the download type require.
2. Extract the ZIP file and open the index.php.
3. Add this code to the index.php.
<?php
require_once('vendor/autoload.php');
/* Start to develop here. Best regards https://php-download.com/ */
dspaccapeli / file-based-router example snippets
// Import the Composer autoloader
= parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH); // e.g. "/" or "/home" or "/api/users"
$directory_path = 'insert here the absolute path to the directory containing the endpoints';
// Route the request
FileBasedRouter::route($url_path, $directory_path);
// Routing
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
$endpoints_abs_path = 'insert here the absolute path to the directory containing the endpoints';
route($path, $endpoints_abs_path, function($path){
return str_contains($path, '.');
}, $return_404, '.view');
FileBasedRouter::route($path, __DIR__ . "/../hello/");
function route (
string $url_path,
string $controller_path = '/var/www/html',
?callable $filter_function = null,
?callable $fallback_handler = null,
?string $view_suffix = null,
string $extension = '.php'
) : bool {
// add index.php to the path if the path is a directory i.e. public/ -> public/index.php
$url_path = substr($url_path, -1) === '/' ? $url_path . 'index' : $url_path;
// if function exists and returns false, call fallback handler
if (isset($filter_function) && $filter_function($url_path)){
isset($fallback_handler) ? $fallback_handler() : http_response_code(404);
return false;
// if file exists redirect there
} else if (file_exists($controller_path . $url_path . $extension)){
// if file exists,