简体   繁体   English

如何使用 PHP 重定向到错误页面?

[英]How can i Redirect to error page using PHP?

Newbie here, I'm trying to redirect to a error page if a controller isn't found from the url.新手,如果从 url 中找不到 controller,我正在尝试重定向到错误页面。 I'm still learning and I have a long way to go and I am really lost on this one.我还在学习,距离 go 还有很长的路要走,我真的迷路了。

code

<?php
    Class App{
        protected $controller   =   'home';
        protected $method       =   'index';
        protected $params       =   [];

        public function __construct(){
            $url    =   $this->parseUrl();

            if(file_exists('assets/includes/controllers/'.$url[0].'.php')){
                $this->controller   =   $url[0];
                unset($url[0]);
            }
            require_once('assets/includes/controllers/'.$this->controller.'.php');

            $this->controller   =   new $this->controller;

            if(isset($url[1])){
                if(method_exists($this->controller,$url[1])){
                    $this->method   =   $url[1];
                    unset($url[1]);
                }
            }
            $this->params   =   $url    ?   array_values($url)  :   [];

            call_user_func_array([$this->controller,$this->method],$this->params);
        }
        public function parseUrl(){
            if(isset($_GET['url'])){
                return $url =   explode('/',filter_var(rtrim($_GET['url'],'/'),FILTER_SANITIZE_URL));
            }
        }
    }
?>

I have tried something like if controller doesn't exist, do this but I can't get it working right, but I know that I'm doing it wrong so I was hoping that someone could point me in the right direction.如果 controller 不存在,我尝试过类似的操作,但我无法让它正常工作,但我知道我做错了,所以我希望有人能指出我正确的方向。

in this scenario you use redirect method like below在这种情况下,您使用如下重定向方法

   if(file_exists('assets/includes/controllers/'.$url[0].'.php')){
            $this->controller   =   $url[0];
            unset($url[0]);
     }
 else 
   {
   header("Location: error.php");
   exit;
   }

This will help you.这将对您有所帮助。

I would do it the other way round - if the controller is not found, import a static error page.我会反过来做 - 如果没有找到 controller,请导入 static 错误页面。

    if(file_exists('assets/includes/controllers/'.$url[0].'.php')){
            $this->controller   =   $url[0];
            unset($url[0]);
        }
   else{
     include 'error_page.php';
     die();
     }

Note: error_page has to be a script that generates error_page output (eg all stuff in the body-tag of your error_page).注意:error_page 必须是生成error_page output 的脚本(例如,error_page 的body-tag 中的所有内容)。 Solution would work, but has to be implemented the right way;)解决方案可行,但必须以正确的方式实施;)

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

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