0

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.

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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 (e.g. all stuff in the body-tag of your error_page). Solution would work, but has to be implemented the right way ;)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.