簡體   English   中英

如何使用 PHP 重定向到錯誤頁面?

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

新手,如果從 url 中找不到 controller,我正在嘗試重定向到錯誤頁面。 我還在學習,距離 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));
            }
        }
    }
?>

如果 controller 不存在,我嘗試過類似的操作,但我無法讓它正常工作,但我知道我做錯了,所以我希望有人能指出我正確的方向。

在這種情況下,您使用如下重定向方法

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

這將對您有所幫助。

我會反過來做 - 如果沒有找到 controller,請導入 static 錯誤頁面。

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

注意:error_page 必須是生成error_page output 的腳本(例如,error_page 的body-tag 中的所有內容)。 解決方案可行,但必須以正確的方式實施;)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM