Skip to content

Instantly share code, notes, and snippets.

@BlackScorp
Last active January 22, 2022 21:01
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BlackScorp/902b7098ebb6a25a287eb96d4b69ba6a to your computer and use it in GitHub Desktop.
Save BlackScorp/902b7098ebb6a25a287eb96d4b69ba6a to your computer and use it in GitHub Desktop.
Code for the Youtube Video https://www.youtube.com/watch?v=enDbYz6weVQ
<IfModule mod_rewrite.c>
Options +FollowSymlinks -Indexes
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME) !-d
RewriteRule ^ index.php [L,QSA]
</IfModule>
<?php
require_once __DIR__.'/router.php';
$getLogin = function() {
$loginForm = <<<HTML
<form method="POST" action="/account/login">
<input type="text" placeholder="username" name="username">
<input type="password" placeholder="password" name="password">
<button>Login</button>
</form>
HTML;
echo $loginForm;
};
$postLogin = function (){
echo "Login erfolgreich";
};
$http404 = function() {
echo '404';
};
class AccountController{
public static function indexAction(){
echo "Hello World";
}
}
router('/', $http404,[AccountController::class,'indexAction']);
router('/account/login', $http404,$getLogin,'GET');
router('/account/login', $http404,$postLogin,'POST');
$requestUrl = $_SERVER['REQUEST_URI'];
$beforeIndexPosition = strpos($_SERVER['PHP_SELF'], '/index.php');
if (false !== $beforeIndexPosition && $beforeIndexPosition > 0) {
$scriptUrl = substr($_SERVER['PHP_SELF'], 0, $beforeIndexPosition).'/';
$requestUrl = str_replace(['/index.php', $scriptUrl], '/', $requestUrl);
}
$requestUrl = $_SERVER['REQUEST_METHOD'].'_'.$requestUrl;
router($requestUrl,$http404);
<?php
function router($path,$http404,$action = null,$methods = 'POST|GET'){
static $routes = [];
if($action){
return $routes['('.$methods.')_'.$path] = $action;
}
foreach ($routes as $route => $action) {
$regEx = "~^$route/?$~i";
$matches = [];
if (!preg_match($regEx, $path, $matches)) {
continue;
}
if (!is_callable($action)) {
return call_user_func_array($http404,$matches);
}
array_shift($matches);
array_shift($matches);
return call_user_func_array($action,$matches);
}
return call_user_func_array($http404,[$path]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment