Created
October 10, 2017 00:44
-
-
Save Ultimater/44d4b0a9b667d75b9967082668605e2a to your computer and use it in GitHub Desktop.
Central file for serving assets through the PHP built-in server, emulating mod_rewrite, redirects, proper headers, and other stuff you'd expect from apache or nginx like caching etc.
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 | |
namespace _htrouter_php; | |
class htRouter | |
{ | |
static public $uri = '', $ext = '', $fullFilePath = ''; | |
static public $mimeTypes = [ | |
'css'=>'text/css', | |
'js'=>'application/javascript', | |
'png'=>'image/png', | |
'gif'=>'image/gif', | |
'jpg'=>'image/jpeg', | |
'txt'=>'text/plain', | |
'ico'=>'image/x-icon' | |
]; | |
static public function parseExt($fullFilePathAndName) | |
{ | |
$path_parts = pathinfo($fullFilePathAndName); | |
self::$ext = $path_parts['extension'] ?? ''; | |
} | |
static public function sendMime() | |
{ | |
if(array_key_exists(self::$ext,self::$mimeTypes)) | |
{ | |
header('Content-Type: '.self::$mimeTypes[self::$ext]); | |
} | |
} | |
static public function serveIfExists() | |
{ | |
if (file_exists(htRouter::$fullFilePath)) | |
{ | |
htRouter::parseExt(htRouter::$fullFilePath); | |
htRouter::sendMime(); | |
if(htRouter::$ext == 'php') | |
{ | |
chdir(dirname(htRouter::$fullFilePath)); | |
require(htRouter::$fullFilePath); | |
exit; | |
} | |
if(is_file(htRouter::$fullFilePath)) | |
{ | |
echo file_get_contents(htRouter::$fullFilePath); | |
exit; | |
} | |
if(is_dir(htRouter::$fullFilePath)) | |
{ | |
if(file_exists(htRouter::$fullFilePath.'/index.php')) | |
{ | |
chdir(dirname(htRouter::$fullFilePath.'/index.php')); | |
require(htRouter::$fullFilePath.'/index.php'); | |
exit; | |
} | |
echo 'nope';exit; | |
} | |
echo 'what';exit; | |
} | |
} | |
} | |
htRouter::$uri = urldecode(parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH)); | |
if (htRouter::$uri !== '/') | |
{ | |
htRouter::$fullFilePath = realpath(__DIR__ . htRouter::$uri); | |
htRouter::serveIfExists(); | |
htRouter::$fullFilePath = realpath(__DIR__ . '/public'.htRouter::$uri); | |
htRouter::serveIfExists(); | |
if(preg_match('#^/([^/]+)/assets/(.+)#', htRouter::$uri, $m)) { | |
header('Location: /core/modules/' . $m[1]. '/assets/'. $m[2], true, 303); | |
exit; | |
} | |
} | |
$_GET['_url'] = htRouter::$uri; | |
chdir(__DIR__.'/public'); | |
require_once __DIR__ . '/public/index.php'; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment