PHP笔记-所有错误统一输出404页面(详细错误日志输出,提高安全性)

x33g5p2x  于2022-03-14 转载在 其他  
字(1.5k)|赞(0)|评价(0)|浏览(178)

这里我用的是自定义MVC,所以统一错误页面很简单,自定义MVC框架在这篇博文

PHP笔记-自定义MVC框架_IT1995的博客-CSDN博客

当输入任意不存在的页面时:

这里在

private static function setDispatch(){

        try{

            $controller = "\\" . P . "\\controller\\" . C . "Controller";
            $action = A;
            $object = new $controller;
            $object->$action();
        }
        catch (\Throwable $e){

            //进入 404页面
            //echo "Message: " . $e->__toString();
            //这里开始 输出到日志

            //这里结束 输出到日志

            self::load404Page();
            $controller = new PageNotFindController();
            $controller->index();
        }
    }

这里使用__toString()可以输出字符串,然后将其输入到服务器日志里面,就能记录日志,不被心怀不轨的人发现了。

这里有一个要注意的地方就是Throwable

/**
 * Throwable is the base interface for any object that can be thrown via a throw statement in PHP 7,
 * including Error and Exception.
 * @link https://php.net/manual/en/class.throwable.php
 * @since 7.0
 */
interface Throwable extends Stringable

这里可以知道,他可以捕获错误和异常,是php7中新引用的。

其中load404Page()函数如下:

private static function load404Page(){

        $controllerFile = APP_PATH . "user/controller/PageNotFindController.php";
        if(file_exists($controllerFile)){

            include $controllerFile;
        }

    }

PageNotFindController.php

<?php

namespace user\controller;

use core\Controller;

class PageNotFindController {

    protected $smarty;

    public function __construct(){

        if(!class_exists("Smarty")){

            include VENDOR_PATH . "smarty/Smarty.class.php";
        }

        $this->smarty = new \Smarty();
        $this->smarty->template_dir = APP_PATH . "user/view/";
        $this->smarty->compile_dir = RESOURCES_PATH . "views";
    }

    public function index(){

        $this->smarty->display("page404.html");
    }
}

这里仅仅能实现功能,提供一个思路。

相关文章

微信公众号

最新文章

更多