简体   繁体   中英

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. I'm still learning and I have a long way to go and I am really lost on this one.

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.

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.

This answer will help you PHP, MVC, 404 - How can I redirect to 404?

I would do it the other way round - if the controller is not found, import a static error page.

    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). Solution would work, but has to be implemented the right way;)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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