Awesome q2a theme

How to make a 404 error in the Router — PHP?

0 like 0 dislike
27 views
Colleagues! How to check in the file Router.php - when entering any wrong link instead of the white screen was a 404 error. At the moment, because of routes like 'category/([a-z]+)' => 'catalog/category/$1', if you enter any incorrect links like site/category/errorlinkkk - displays the category you want. You need to trigger the 404 error. Code training, implement for your project, and train. Sincerely, Alexander!

File Router.php

class Router { private $routes; //array that will store ranting public function __construct() { $routesPath = ROOT.'/config/routes.php'; //path to ranting $this->routes = include($routesPath); } private function getURI() { if (!empty($_SERVER['REQUEST_URI'])) { return trim($_SERVER['REQUEST_URI'], '/'); } } public function run() { //Get the query string $uri = $this->getUri(); //Check the presence of such a request in routes.php foreach($this->routes as $uriPattern => $path) { //Compare $uriPattern $uri if (preg_match("~^$uriPattern$~", $uri)) { //Get the internal path of the external rule $internalRoute = preg_replace("~$uriPattern~", $path, $uri); //Determine which controller and method to handle the request $segments = explode('/', $internalRoute); //Get the controller name $controllerName = ucfirst(array_shift($segments)).'Controller'; //Get the method name $actionName = 'action'.ucfirst(array_shift($segments)); //Connect the controller class file $controllerFile = ROOT . '/controllers/' . $controllerName . '.php'; if (file_exists($controllerFile)) { include_once($controllerFile); } //Create the object to call the method $parameters = $segments; $controllerObject = new $controllerName; $result = call_user_func_array(array($controllerObject, $actionName), $parameters); if($result != null) { break; } } } } }


Part of the code of routes.php

return array( // Item: 'product/([a-z]+)' => 'product/view/$1', // actionView in ProductController // Catalog: 'catalog' => 'catalog/index', // actionIndex in CatalogController // Category of the goods: '([0-9]+)/page-([0-9]+)' => 'catalog/category/$1/$2', // actionCategory in CatalogController 'category/([a-z]+)' => 'catalog/category/$1', // actionCategory in CatalogController );
by | 27 views

2 Answers

0 like 0 dislike
You can make a controller for the 404 error and make it last. The regular season just to him *
by
0 like 0 dislike
Suggested this code, but can't catch up with what you need to compare to output file error

if (basename($_SERVER['SCRIPT_FILENAME']) == basename(__FILE__)) { header('Location: error404.php'); exit; }
by

Related questions

0 like 0 dislike
2 answers
0 like 0 dislike
1 answer
0 like 0 dislike
1 answer
asked May 21, 2019 by Artur937
0 like 0 dislike
1 answer
110,608 questions
257,187 answers
0 comments
40,796 users