Created
January 26, 2020 01:13
-
-
Save ricardoboss/e04f00a4ba182d33b2a1faf6f0d3338e to your computer and use it in GitHub Desktop.
Simple php built-in webserver router script.
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 | |
define('PUBLIC_DIR', __DIR__ . DIRECTORY_SEPARATOR . 'public'); | |
$uri = $_SERVER['REQUEST_URI']; | |
// assume path exists in public directory | |
$path = PUBLIC_DIR . $uri; | |
// convert to realpath and substitute '.' and '..' | |
$real = realpath($path); | |
if ($real === false) { | |
http_response_code(404); | |
echo "resource not found"; | |
return true; | |
} | |
// check if we are still in the public dir ('..' could have been used to change directories) | |
if (mb_strpos($real, PUBLIC_DIR) === false) { | |
http_response_code(400); | |
echo "invalid uri"; | |
return true; | |
} | |
$exists = false; | |
if (is_dir($real)) { | |
// check if the directory contains an index file | |
foreach (['index.php', 'index.html', 'default.php', 'default.html'] as $indexFile) | |
if (file_exists($real . DIRECTORY_SEPARATOR . $indexFile)) { | |
// append index file path | |
$real .= DIRECTORY_SEPARATOR . $indexFile; | |
$exists = true; | |
break; | |
} | |
} else { | |
// check if the file exists | |
$exists = file_exists($real); | |
} | |
// return 404 if nothing was found | |
if (!$exists) { | |
http_response_code(404); | |
echo "resource not found"; | |
return true; | |
} | |
// check if static files are requested | |
switch (pathinfo($real, PATHINFO_EXTENSION)) { | |
case 'css': | |
case 'js': | |
case 'ico': | |
case 'png': | |
case 'jpg': | |
return false; | |
} | |
require $real; | |
return true; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment