簡體   English   中英

PHP 路由 - 如何在錯誤的 url 路由上實現 404 頁面?

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

每個人。

我有一個在 PHP 中創建的基本路由器。

我可以重定向到我想要的任何頁面,如果有回調 function,回調 function 將被執行,如果有頁面(字符串而不是函數),頁面加載正確的文件。 但是我不知道如何在不存在的路由上實現 404 頁面。

我嘗試重用 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
}

這是我的代碼。

<?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();

?>

您可以在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