Skip to content

Instantly share code, notes, and snippets.

@jongacnik
Last active August 7, 2022 16:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jongacnik/e0b44b350faef660bbfc8b2adcc9f297 to your computer and use it in GitHub Desktop.
Save jongacnik/e0b44b350faef660bbfc8b2adcc9f297 to your computer and use it in GitHub Desktop.
Built-in PHP server router
<?php
/**
* Built-in PHP server router:
*
* - If file exists, serve file
* - Access php files without .php extension
* - Unknown routes throw 404
* - Optionally fallback to index.php
*
* <Folder Studio>
*/
$uri = trim(urldecode(
parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)
), '/');
// Emulate Apache's `mod_rewrite` functionality
if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/' . $uri)) {
return false;
}
// Allow .php files without extension
if (file_exists($_SERVER['DOCUMENT_ROOT'] . '/' . $uri . '.php')) {
require $_SERVER['DOCUMENT_ROOT'] . '/' . $uri . '.php';
return true;
}
// // Fallback to index
// require $_SERVER['DOCUMENT_ROOT'] . '/index.php';
// return true;
// Throw 404 on invalid route
http_response_code(404); ?>
<h1>Not Found</h1>
<p>The requested resource <code><?= $_SERVER['REQUEST_URI'] ?></code> was not found on this server.</p>
php -S localhost:3001 -t public router.php
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment