繁体   English   中英

通过使用漂亮的URL将用户重定向到404页面

[英]Redirecting users to a 404 page by using pretty urls

我正在做一个mvc项目,只是为了好玩。 漂亮的网址已经可以使用,但是我无法找到一种很好的方法将我的代码发送给404页面,以防人们所寻找的页面不存在。

class Route
{
       private $_uri = array();
       private $_method = array();

    /*
     * Builds a collection of internal URL's to look for
     * @param type $uri
     */
    public function add($uri, $method = null)
    {
        $this->_uri[] = '/' . trim($uri, '/');

        if($method != null){
            $this->_method[] = $method;
        }
    }

    public function submit()
    {

        $uriGetParam = isset($_GET['uri']) ? '/' . $_GET['uri'] : '/';

        foreach($this->_uri as $key => $value){
            if(preg_match("#^$value$#",$uriGetParam)){
                if(is_string($this->_method[$key])){
                    $useMethod = $this->_method[$key];
                    new $useMethod();
                }
                else{
                    call_user_func($this->_method[$key]);
                }
            }
        }
    }

}

我没有彻底分析您的代码(我不能,不确定使用-> add添加的示例路由/方法是什么),但是解决方案对我来说似乎很简单:

public function submit()
{

    $uriGetParam = isset($_GET['uri']) ? '/' . $_GET['uri'] : '/';
    $routeFound = false;
    foreach($this->_uri as $key => $value){
        if(preg_match("#^$value$#",$uriGetParam)){
            if(is_string($this->_method[$key])){
                $routeFound = true; 
                $useMethod = $this->_method[$key];
                new $useMethod();
            }
            else{
                $routeFound = true; 
                call_user_func($this->_method[$key]);
            }
        }
    }
    if(!$routeFound){ 
        http_response_code(404);
        echo 'ooooh, not found'; 
        //or:
        include('404.php');
        die();
    }
}

ps http_response_code是一个内置函数:

https://secure.php.net/manual/zh/function.http-response-code.php

编辑:您可以将代码以“ http_response_code(404);”开头 到一个单独的函数,然后调用它。

暂无
暂无

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

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