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

这里我用的是自定义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");
    }
}

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

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT1995

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值