简体   繁体   English

PHP 路由 - 如何在错误的 url 路由上实现 404 页面?

[英]PHP routing - How can I implement 404 page on wrong url routes?

everyone.每个人。

I have a basic router created in PHP.我有一个在 PHP 中创建的基本路由器。

I can redirect to any page I want, if there is a callback function the callback function gets executed and if there is a page (String instead of a function) the page loads the correct file.我可以重定向到我想要的任何页面,如果有回调 function,回调 function 将被执行,如果有页面(字符串而不是函数),页面加载正确的文件。 However I can't figure out how to implement 404 page on non-existing route.但是我不知道如何在不存在的路由上实现 404 页面。

I tried to reuse the preg_match() function, but that gave me no results and if I place the notFound() (404 page) in the else block, it always gets executed regardless of the correct url or not.我尝试重用 preg_match() function,但这没有给我任何结果,如果我将 notFound() (404 页)放在 else 块中,无论 url 是否正确,它总是会被执行。

if(preg_match($pattern, $path, $matches) && $httpMethod === $route['method']) {

}else{
     self::notFound(); //THIS GETS EXECUTED ON EVERY ROUTE
}

This is my Code.这是我的代码。

<?php

class Router{

    public static $routes = [];

    public static function get($route, $callback){
        self::$routes[] = [
            'route' => $route,
            'callback' => $callback,
            'method' => 'GET'
        ];

       
    }

    public static function resolve(){
        $path = $_SERVER['REQUEST_URI'];
        $httpMethod = $_SERVER['REQUEST_METHOD'];

        $methodMatch = false;
        $routeMatch = false;

        foreach(self::$routes as $route){

            // convert urls like '/users/:uid/posts/:pid' to regular expression
            $pattern = "@^" . preg_replace('/\\\:[a-zA-Z0-9\_\-]+/', '([a-zA-Z0-9\-\_]+)', preg_quote($route['route'])) . "$@D";
            $matches = Array();


            // check if the current request matches the expression
            if(preg_match($pattern, $path, $matches) && $httpMethod === $route['method']) {
                // remove the first match
                array_shift($matches);
                // call the callback with the matched positions as params

                if(is_callable($route['callback'])){
                    call_user_func_array($route['callback'], $matches);
                }else{
                    self::render($route['callback']);

                }
            }
        }
      
    }

    public static function render($file, $viewsFolder='./views/'){
        include($viewsFolder . $file);

    }

    public static function notFound(){
        http_response_code(400);
        include('./views/404.php');
        exit();
    }
}

Router::get("/", "home.php");
Router::get("/user/:id", function($val1) {
    $data = array(
        "Nicole",
        "Sarah",
        "Jinx",
        "Sarai"
    );

    echo $data[$val1] ?? "No data";
});

Router::get("/user/profile/:id", "admin.php");
Router::resolve();

?> ?>

You can add notFound() at the very end of resolve() method, and a return when you hit a match:您可以在resolve()方法的最后添加notFound() ,并在匹配时return

public static function resolve(){
    $path = $_SERVER['REQUEST_URI'];
    $httpMethod = $_SERVER['REQUEST_METHOD'];

    $methodMatch = false;
    $routeMatch = false;

    foreach(self::$routes as $route){
        $pattern = "@^" . preg_replace('/\\\:[a-zA-Z0-9\_\-]+/', '([a-zA-Z0-9\-\_]+)', preg_quote($route['route'])) . "$@D";
        $matches = Array();

        if(preg_match($pattern, $path, $matches) && $httpMethod === $route['method']) {                
            array_shift($matches);
            if(is_callable($route['callback'])){
                call_user_func_array($route['callback'], $matches);
            }else{
                self::render($route['callback']);
            }
            return;
        }           
    }
    notFound();
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM