php -S localhost:3001 -t public router.php
Last active
August 7, 2022 16:10
-
-
Save jongacnik/e0b44b350faef660bbfc8b2adcc9f297 to your computer and use it in GitHub Desktop.
Built-in PHP server router
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment