protected function execute() { $pathinfo = pathinfo($this->server->getParam('SCRIPT_NAME')); $basePath = $pathinfo['dirname']; $router = new \AltoRouter(); $router->setBasePath($basePath); $routes = $this->metadata->getMetadata('routes'); foreach ($routes as $route) { $router->map($route['method'], $route['rule'], $route['target']); } $match = $router->match(); if (!empty($match)) { $this->parameters = array_merge($match['target'], $match['params']); } }
/** * Handles a Request to convert it to a Response. * * When $catch is true, the implementation must catch all exceptions * and do its best to convert them to a Response instance. * * @param Request $request A Request instance * @param int $type The type of the request * (one of HttpKernelInterface::MASTER_REQUEST or HttpKernelInterface::SUB_REQUEST) * @param bool $catch Whether to catch exceptions or not * * @return Response A Response instance * * @throws \Exception When an Exception occurs during processing */ public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true) { try { $match = $this->routeMatch; if (!$match) { $match = $this->router->match($request->getPathInfo()); } if ($match) { list($module, $controller, $action) = $this->processRoute($match); $request->attributes->add(['_module' => $module, '_controller' => $controller, '_action' => $action]); $response = $this->dispatcher->dispatch($match['target'], $match['params']); } else { $response = $this->dispatcher->dispatch('Home#error', ['message' => 'Halaman tidak ditemukan: ' . $request->getPathInfo()]); $response->setStatusCode(Response::HTTP_NOT_FOUND); } } catch (HttpException $e) { if (!$catch) { throw $e; } $response = $this->dispatcher->dispatch('Home#error', ['message' => '[' . $e->getCode() . '] ' . $e->getMessage()]); $response->setStatusCode($e->getStatusCode()); } catch (Exception $e) { if (!$catch) { throw $e; } $response = $this->dispatcher->dispatch('Home#error', ['message' => '[' . $e->getCode() . '] ' . $e->getMessage()]); $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR); } //$response->setMaxAge(300); return $response; }
public function handle(Request $request, $type = self::MASTER_REQUEST, $catch = true) { $match = $this->router->match($request->getPathInfo()); $route = substr($request->getPathInfo(), strlen(rtrim($this->config['baseDir'], '/'))); if ($match) { $tokenValid = false; $jwtCookie = $this->config['jwt']['cookieName']; $jwtKey = $this->config['jwt']['key']; // check token from cookie if ($request->cookies->has($jwtCookie)) { $jwt = $request->cookies->get($jwtCookie); try { $decoded = JWT::decode($jwt, $jwtKey, ['HS256']); if ($decoded->e > time()) { $tokenValid = true; $this->auth->init($decoded->uid); } } catch (\Exception $e) { $tokenValid = false; if (!$catch) { throw $e; } $response = $this->dispatcher->dispatch('Home#error', ['message' => '[' . $e->getCode() . '] ' . $e->getMessage() . '<pre>' . $e->getTraceAsString() . '</pre>']); $response->setStatusCode(Response::HTTP_INTERNAL_SERVER_ERROR); return $response; } } $allowed = false; $isPublic = false; foreach ($this->config['publicArea'] as $publicRoute) { if (preg_match('/^' . addcslashes($publicRoute, '/') . '/', $route)) { $isPublic = true; break; } } if ($match['name'] == 'home') { $isPublic = true; } if ($isPublic) { if ($route == '/login' && $tokenValid) { return new RedirectResponse($this->router->generate('dashboard')); } $allowed = true; } else { $allowed = $tokenValid; } if ($allowed) { $this->app->setRouteMatch($match); return $this->app->handle($request, $type, $catch); } else { $this->flash->warning('Sesi Anda telah habis atau Anda tidak berhak mengakses halaman ini, silakan login terlebih dahulu!'); $response = $this->dispatcher->dispatch('User#login', []); $response->setStatusCode(Response::HTTP_UNAUTHORIZED); return $response; } } $response = $this->dispatcher->dispatch('Home#error', ['message' => 'Halaman tidak ditemukan: ' . $route]); $response->setStatusCode(Response::HTTP_NOT_FOUND); return $response; }
/** * @param Request $request * @return mixed|JsonResponse|Response */ protected function handle(Request $request = null) { try { $this->response = $this->get('Response'); // dispatch app-start events $this->eventDispatcher->emit('app-start'); $matchedRoutes = $this->router->match(); if ($matchedRoutes === false) { // dispatch app-failed-dispatch events $this->eventDispatcher->emit('app-failed-dispatch', 404); } else { // dispatch app-before-dispatch events $this->eventDispatcher->emit('app-before-dispatch'); list($controller, $action) = explode(":", $matchedRoutes['target']); $controller = $this->container->get('\\App\\Http\\' . $controller); $methodResolver = new MethodResolver($controller, $action, $matchedRoutes['params']); $methodArguments = $methodResolver->getMethodArguments(); $response = call_user_func_array(array($controller, $action), $methodArguments); $this->processResponseType($response); // dispatch app-before-dispatch events $this->eventDispatcher->emit('app-after-dispatch'); } $this->response->send(); } catch (\Exception $e) { $this->eventDispatcher->emit('app-error', 500, $e); } // dispatch app-start events $this->eventDispatcher->emit('app-end'); }
/** * Call controller by route * * @param string $route * @return mixed * @throws \Exception If no matching route was found * @throws \Exception If matching route is not callable */ public function callController($route = null, $method = null) { // Get matching route $match = $this->router->match($route, $method); if ($match === false) { throw new \Exception('No matching route found!'); } else { if (is_callable($match['target']) === false) { throw new \Exception('Matching route is not callable!'); } } // Add dependencies $dependencies = $this->getDependencies(); $dependencies->setParameter('controllerParams', $match['params']); // Call function return call_user_func_array($match['target'], array('dependencies' => $dependencies)); }
public function testMatchWithCustomNamedRegex() { $this->router->addMatchTypes(array('cId' => '[a-zA-Z]{2}[0-9](?:_[0-9]++)?')); $this->router->map('GET', '/bar/[cId:customId]', 'bar_action', 'bar_route'); $this->assertEquals(array('target' => 'bar_action', 'params' => array('customId' => 'AB1'), 'name' => 'bar_route'), $this->router->match('/bar/AB1', 'GET')); $this->assertEquals(array('target' => 'bar_action', 'params' => array('customId' => 'AB1_0123456789'), 'name' => 'bar_route'), $this->router->match('/bar/AB1_0123456789', 'GET')); $this->assertFalse($this->router->match('/some-other-thing', 'GET')); }
/** * Performs a dispatching mechanism. * * @return void */ public function dispatch() { $match = $this->altoRouter->match(); if (!$match) { container("ViewContract")->render("errors.404")->withCode(404); // TODO: be sure that errors.404 exists - check it! Allow user add custom 404 file. exit; } $this->processMatch($match); }
public function testMatchWithCustomNamedUnicodeRegex() { $pattern = '[^'; // Arabic characters $pattern .= '\\x{0600}-\\x{06FF}'; $pattern .= '\\x{FB50}-\\x{FDFD}'; $pattern .= '\\x{FE70}-\\x{FEFF}'; $pattern .= '\\x{0750}-\\x{077F}'; $pattern .= ']+'; $this->router->addMatchTypes(array('nonArabic' => $pattern)); $this->router->map('GET', '/bar/[nonArabic:string]', 'non_arabic_action', 'non_arabic_route'); $this->assertEquals(array('target' => 'non_arabic_action', 'name' => 'non_arabic_route', 'params' => array('string' => 'some-path')), $this->router->match('/bar/some-path', 'GET')); $this->assertFalse($this->router->match('/﷽', 'GET')); }
/** * This function runs the router and call the apropriate */ public function run($url = null, $method = null) { $route = $this->altoRouter->match($url, $method); if (!$route) { throw new NotFoundException((isset($_SERVER['REQUEST_URI']) && !empty($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : ($url != null ? $url : "/")) . " is not reachable."); } if (!isset($route['target']['c']) || !isset($route['target']['a']) || !isset($route['params'])) { throw new FrameworkException('Internal Framework Error. [!BAD_ROUTER_TARGET]', 01); } if (is_callable(array($route['target']['c'], 'getInstance'))) { $controller = $route['target']['c']::getInstance(); if (method_exists($controller, $route['target']['a'])) { call_user_func(array($controller, $route['target']['a']), array_values($route['params'])); $controller->response->send(); } else { throw new FrameworkException('Internal Framework Error. [METHOD_DOES_NOT_EXISTS]', 02); } } else { throw new FrameworkException('Internal Framework Error. [CONTROLLER_DOES_NOT_EXISTS]', 03); } }
/** * Démarrage de l'application. */ public function run() { $router = new \AltoRouter(); if (isset($_SERVER['BASE'])) { $router->setBasePath($_SERVER['BASE']); } $router->map('GET', '/', function () { $this->startControllerAction('Public', 'index'); }, 'home'); $router->map('GET|POST|PATCH|PUT|DELETE', '/[a:controller]/[a:action]', function ($controller, $action) { $this->startControllerAction(ucfirst($controller), $action); }, 'action'); if (($match = $router->match()) !== false) { call_user_func_array($match['target'], $match['params']); } else { header("{$_SERVER['SERVER_PROTOCOL']} 404 Not Found"); } }
<?php use Otik\Config; use Tracy\Debugger; use Otik\Output; require_once 'vendor/autoload.php'; $config = new Config(dirname(__FILE__) . DIRECTORY_SEPARATOR . 'config'); Debugger::enable(Debugger::DETECT, dirname(__FILE__) . DIRECTORY_SEPARATOR . 'log', $config->get('dev.email')); $router = new AltoRouter(); $router->map('OPTIONS', '/series/[*:series]/events', 'Options::optionsForEvents', 'optionsForEvents'); $router->map('POST', '/series/[*:series]/events', 'Event::postToEvents', 'postToEvents'); if (isset($_REQUEST['_method'])) { $matched = $router->match(null, $_REQUEST['_method']); } else { $matched = $router->match(); } if ($matched === false) { $o = new Output(); $o->return404(); } list($wantedController, $wantedAction) = explode('::', $matched['target']); $controllerClassName = 'Otik\\' . $wantedController; if (!class_exists($controllerClassName)) { throw new RuntimeException('Target class (' . $controllerClassName . ') doesn\'t exists or cann\'t be autoloaded'); } $controller = new $controllerClassName($config); if (!method_exists($controller, $wantedAction)) { throw new RuntimeException('Target class doesn\'t have method ' . $wantedAction . '.'); } call_user_func_array(array($controller, $wantedAction), $matched['params']);
public function match($requestUrl = null, $requestMethod = null) { return $this->altoRouter->match($requestUrl, $requestMethod); }
$router->map('POST', '/guestbook/create', 'GuestbookController@create'); $router->map('GET|POST', '/guestbook/[i:id]/edit', 'GuestbookController@edit'); $router->map('GET|POST', '/guestbook/[i:id]/reply', 'GuestbookController@reply'); $router->map('POST', '/guestbook/delete', 'GuestbookController@delete'); $router->map('GET', '/forum', 'ForumController@index', 'forum'); $router->map('GET', '/forum/[i:id]', 'ForumController@forum'); $router->map('GET', '/topic/[i:id]', 'ForumController@topic'); $router->map('POST', '/topic/bookmark', 'ForumController@bookmark'); $router->map('POST', '/topic/[i:id]/create', 'ForumController@createPost'); $router->map('GET|POST', '/forum/create', 'ForumController@createTopic'); $router->map('GET|POST', '/post/[i:id]/edit', 'ForumController@editPost'); $router->map('GET', '/news', 'NewsController@index', 'news'); $router->map('GET', '/news/[i:id]', 'NewsController@view', 'news_view'); $router->map('GET|POST', '/news/create', 'NewsController@create'); $router->map('POST', '/news/comment', 'NewsController@createComment'); $router->map('GET', '/news/rss', 'NewsController@rss', 'news_rss'); $router->map('POST', '/news/tags', 'NewsController@tags'); $router->map('GET', '/category', 'CategoryController@index'); $router->map('GET|POST', '.category/create', 'CategoryController@create'); $router->map('GET|POST', '/category/[i:id]/edit', 'CategoryController@edit'); $router->map('POST', '/category/delete', 'CategoryController@delete'); $router->map('GET', '/admin', 'AdminController@index', 'admin'); /* $router->map('GET', '/[guestbook|forum|news:link]/smiles/page/[i:page]', 'pages/smiles'); $router->map('GET', '/[guestbook|forum|news:link]/smiles', 'pages/smiles'); $router->map('GET', '/[guestbook|forum|news:link]/tags', 'pages/tags'); */ $router->map('GET', '/[slug:category]', 'NewsController@view'); $router->map('GET', '/[slug:category]/[slug:news]', 'NewsController@view'); Registry::set('router', $router->match());
/** * Map a resource to its corresponding controller * * @since 0.1.0 * @access public * @param array $path URI path array * @param string $method HTTP method * @param array $data Request arguments * @return array Dispatch instruction for Garden. * @static */ public static function map($resource, $class, $path, $method, $data) { $router = new AltoRouter(); $router->setBasePath("/api"); $endpoints = $class->endpoints($data); if ($method == "options") { $supports = strtoupper(implode(", ", $class::supports())); $documentation = []; foreach ($endpoints as $method => $endpoints) { foreach ($endpoints as $endpoint => $data) { $documentation[$method][] = paths($resource, $endpoint); } } $documentation = base64_encode(json_encode($documentation)); return ["application" => "API", "controller" => "API", "method" => "options", "arguments" => [$supports, $documentation], "authenticate" => false]; } else { // Register all endpoints in the router foreach ($endpoints as $method => $endpoints) { foreach ($endpoints as $endpoint => $data) { $endpoint = "/" . $resource . rtrim($endpoint, "/"); $router->map($method, $endpoint, $data); } } $match = $router->match("/" . rtrim(join("/", $path), "/")); if (!$match) { throw new Exception(t("API.Error.MethodNotAllowed"), 405); } $target = val("target", $match); $arguments = array_merge(val("params", $match, []), val("arguments", $target, [])); return ["application" => val("application", $target, false), "controller" => val("controller", $target), "method" => val("method", $target, "index"), "authenticate" => val("authenticate", $target), "arguments" => $arguments]; } }
require 'vendor/autoload.php'; // Import the necessary classes use Illuminate\Database\Capsule\Manager as Capsule; // Include the composer autoload file // Setup a new Eloquent Capsule instance $capsule = new Capsule(); $capsule->addConnection(['driver' => 'mysql', 'host' => '127.0.0.1', 'database' => 'cs', 'username' => 'root', 'password' => '', 'charset' => 'utf8', 'collation' => 'utf8_unicode_ci']); $capsule->bootEloquent(); $router = new AltoRouter(); $router->setBasePath('/cs'); $router->map('GET|POST', '/', 'home#index', 'home'); $router->map('GET', '/users/', array('c' => 'UserController', 'a' => 'ListAction')); $router->map('GET', '/api/course/all/', 'Api#allCourses'); $router->map('GET', '/api/course/[i:id]/', 'Api#getCourse'); $router->map('GET', '/api/user/all/', 'Api#allUsers'); $router->map('POST', '/api/user/new/', 'Api#newUser'); $router->map('GET', '/api/user/[*:id]/', 'Api#getUser'); $router->map('GET', '/api/cron/', 'Api#cron'); // match current request $match = $router->match(); if ($match) { $path = explode('#', $match['target']); $controller = $path[0]; $method = $path[1]; $params = $match['params']; $object = new $controller(); $object->{$method}($params); } else { (new Controller())->index(); }
// grab status definitions require SCRIPTROOT . 'statusdefs.php'; // set timezone date_default_timezone_set('UTC'); // setup cache require SCRIPTROOT . 'phpfastcache/phpfastcache.php'; phpFastCache::setup('storage', 'files'); phpFastCache::setup('path', ROOT . 'cache'); $cache = phpFastCache(); // setup routing require SCRIPTROOT . 'AltoRouter/AltoRouter.php'; $routes = new AltoRouter(); // load the actual routes require ROOT . 'routes.php'; // handle the route request $route = $routes->match(); // error page handling function ErrorPage($Error) { ob_get_clean(); http_response_code($Error); $error = $Error; require VIEWROOT . 'error.php'; die; } if (!$route) { ErrorPage(404); } else { // get route target information $target = $route['target']; // all API requests will use a HTTP GET request method
$apiRouter->map('POST', '/market/job/create', array('c' => 'JobMarket', 'a' => 'create', 'authtoken' => true, 'usertoken' => true, 'official' => true)); $apiRouter->map('POST', '/market/job/offers', array('c' => 'JobMarket', 'a' => 'offers')); // COMPANY $apiRouter->map('POST', '/company/get', array('c' => 'Company', 'a' => 'get', 'authtoken' => true, 'usertoken' => true)); $apiRouter->map('POST', '/company/create', array('c' => 'Company', 'a' => 'create', 'authtoken' => true, 'usertoken' => true, 'official' => true)); $apiRouter->map('POST|GET', '/company/list', array('c' => 'Company', 'a' => 'getList', 'authtoken' => true, 'usertoken' => true)); // RESOURCE $apiRouter->map('GET', '/resource/get', array('c' => 'Resource', 'a' => 'get')); $apiRouter->map('GET', '/resource/list', array('c' => 'Resource', 'a' => 'getList')); $apiRouter->map('POST', '/resource/create', array('c' => 'Resource', 'a' => 'create')); // PRODUCT $apiRouter->map('GET', '/product/get', array('c' => 'Product', 'a' => 'get')); $apiRouter->map('GET', '/product/list', array('c' => 'Product', 'a' => 'getList')); $apiRouter->map('POST', '/product/create', array('c' => 'Product', 'a' => 'create')); // REGION $apiRouter->map('GET', '/region/get', array('c' => 'Region', 'a' => 'get')); $apiRouter->map('GET', '/region/list', array('c' => 'Region', 'a' => 'getList')); $apiRouter->map('POST', '/region/create', array('c' => 'Region', 'a' => 'create')); $match = $apiRouter->match(); $api = new Api($_REQUEST['authtoken'], $_REQUEST['usertoken']); if (!$match) { echo $api->replyError('Invalid call'); } else { $call = $match['target']; $isOk = $api->checkSecurity($call['authtoken'], $call['usertoken'], $call['official']); if ($isOk === true) { echo $api->exec($call['c'], $call['a']); } else { echo $isOk; } }
/** * Match a given request url against stored routes * * @param string $request_url * @param string $request_method * * @return array boolean with route information on success, false on failure (no match). */ public function match($request_url = null, $request_method = null) { // Set Request Url if it isn't passed as parameter if ($request_url === null) { $request_url = isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/'; } $this->request_url = $request_url; // Set Request Method if it isn't passed as a parameter if ($request_method === null) { $request_method = isset($_SERVER['REQUEST_METHOD']) ? $_SERVER['REQUEST_METHOD'] : 'GET'; } // Is this an ajax request? if (substr($request_url, -5) == '/ajax') { $this->ajax = true; $request_url = str_replace('/ajax', '', $request_url); } elseif (isset($_GET['ajax'])) { $this->ajax = true; } $this->match = parent::match($request_url, $request_method); if (!empty($this->match)) { // Some parameters only have control or workflow character and are no parameters for public use. // Those will be removed from the parameters array after using them to set corresponding values and/or flags // in router. $controls = ['ajax', 'format']; foreach ($controls as $key) { if (isset($this->match['params'][$key])) { switch ($key) { case 'ajax': $this->ajax = true; break; case 'format': $this->format = $this->match['params'][$key]; break; default: $this->{$key} = $this->match['params'][$key]; } break; } unset($this->match['params'][$key]); } } if (!empty($this->match['params'])) { foreach ($this->match['params'] as $key => $val) { if (empty($val)) { unset($this->match['params'][$key]); } if (in_array($key, $this->parameter_to_target)) { $this->match['target'][$key] = $val; } } } }
public function init() { $this->load->helper('url'); if (!file_exists(APPPATH . '/config/database.php')) { redirect('install'); exit; } session_start(); //set the session userdata if non-existant if (!isset($_SESSION['userdata'])) { $_SESSION['userdata'] = []; } //set newFlashdata if non-existent if (!isset($_SESSION['newFlashdata'])) { $_SESSION['newFlashdata'] = []; } //empty out the "oldFlashdata" field $_SESSION['oldFlashdata'] = []; //shift newFlashdata over to oldFlashdata $_SESSION['oldFlashdata'] = $_SESSION['newFlashdata']; $_SESSION['newFlashdata'] = []; //module list $GLOBALS['modules'] = []; if (!file_exists(APPPATH . 'config/manifest.php')) { $this->load->helper('file'); $manifest = "<?php defined('BASEPATH') OR exit('No direct script access allowed');\n//DO NOT EDIT THIS FILE\n\n"; $this->classMap = []; $paths = [FCPATH . 'addons', APPPATH . 'modules', APPPATH . 'libraries', APPPATH . 'core']; $paymentModules = []; $shippingModules = []; $themeShortcodes = []; $routes = []; $modules = []; //just modules $moduleDirectories = [APPPATH . 'modules', FCPATH . 'addons']; foreach ($moduleDirectories as $moduleDirectory) { foreach (array_diff(scandir($moduleDirectory), ['..', '.']) as $availableModule) { if (is_dir($moduleDirectory . '/' . $availableModule)) { //create a codeigniter package path to the module. //$this->load->add_package_path($moduleDirectory.'/'.$availableModule); $modules[] = $moduleDirectory . '/' . $availableModule; } } } foreach ($paths as $path) { $dir_iterator = new RecursiveDirectoryIterator($path); $iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST); foreach ($iterator as $file) { if (!is_dir($file)) { $ext = pathinfo($file, PATHINFO_EXTENSION); $filename = pathinfo($file, PATHINFO_FILENAME); if ($ext == 'php') { if ($filename == 'manifest') { include $file; } $this->getPhpClasses((string) $file); } } } } $manifest .= '//ClassMap for autoloader' . "\n" . '$classes = ' . var_export($this->classMap, true) . ';'; $manifest .= "\n\n" . '//Available Payment Modules' . "\n" . '$GLOBALS[\'paymentModules\'] =' . var_export($paymentModules, true) . ';'; $manifest .= "\n\n" . '//Available Shipping Modules' . "\n" . '$GLOBALS[\'shippingModules\'] = ' . var_export($shippingModules, true) . ';'; $manifest .= "\n\n" . '//Theme Shortcodes' . "\n" . '$GLOBALS[\'themeShortcodes\'] = ' . var_export($themeShortcodes, true) . ';'; $manifest .= "\n\n" . '//Complete Module List' . "\n" . '$GLOBALS[\'modules\'] = ' . var_export($modules, true) . ';'; $manifest .= "\n\n" . '//Defined Routes' . "\n" . '$routes = ' . var_export($routes, true) . ';'; //generate the autoload file write_file(APPPATH . 'config/manifest.php', $manifest); } require APPPATH . 'config/manifest.php'; //load in the database. $this->load->database(); //set up routing... $router = new \AltoRouter(); $base = trim($_SERVER['BASE'], '/'); if ($base != '') { $router->setBasePath('/' . $base); } //set the homepage route $router->map('GET|POST', '/', 'GoCart\\Controller\\Page#homepage'); //map the routes from the manifest. foreach ($routes as $route) { $router->map($route[0], $route[1], $route[2]); } foreach ($GLOBALS['modules'] as $module) { $this->load->add_package_path($module); } //autoloader for Modules spl_autoload_register(function ($class) use($classes) { if (isset($classes[$class])) { include $classes[$class]; } }); //autoload some libraries here. $this->load->model('Settings'); $this->load->library(['session', 'auth', 'form_validation']); $this->load->helper(['file', 'string', 'html', 'language', 'form', 'formatting']); //get settings from the DB $settings = $this->Settings->get_settings('gocart'); //loop through the settings and set them in the config library foreach ($settings as $key => $setting) { //special for the order status settings if ($key == 'order_statuses') { $setting = json_decode($setting, true); } //other config items get set directly to the config class $this->config->set_item($key, $setting); } date_default_timezone_set(config_item('timezone')); //if SSL is enabled in config force it here. if (config_item('ssl_support') && (!isset($_SERVER['HTTPS']) || $_SERVER['HTTPS'] == 'off')) { $this->config->set_item('base_url', str_replace('http://', 'https://', config_item('base_url'))); redirect(\CI::uri()->uri_string()); } //do we have a dev username & password in place? //if there is a username and password for dev, require them if (config_item('stage_username') != '' && config_item('stage_password') != '') { if (!isset($_SERVER['PHP_AUTH_USER'])) { header('WWW-Authenticate: Basic realm="Login to restricted area"'); header('HTTP/1.0 401 Unauthorized'); echo config_item('company_name') . ' Restricted Location'; exit; } else { if (config_item('stage_username') != $_SERVER['PHP_AUTH_USER'] || config_item('stage_password') != $_SERVER['PHP_AUTH_PW']) { header('WWW-Authenticate: Basic realm="Login to restricted area"'); header('HTTP/1.0 401 Unauthorized'); echo 'Restricted Location'; exit; } } } // lets run the routes $match = $router->match(); // call a closure if ($match && is_callable($match['target'])) { call_user_func_array($match['target'], $match['params']); } elseif ($match && is_string($match['target'])) { $target = explode('#', $match['target']); try { $class = new $target[0](); call_user_func_array([$class, $target[1]], $match['params']); } catch (Exception $e) { var_dump($e); throw_404(); } } else { throw_404(); } }