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

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

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

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

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

这里在

  1. private static function setDispatch(){
  2. try{
  3. $controller = "\\" . P . "\\controller\\" . C . "Controller";
  4. $action = A;
  5. $object = new $controller;
  6. $object->$action();
  7. }
  8. catch (\Throwable $e){
  9. //进入 404页面
  10. //echo "Message: " . $e->__toString();
  11. //这里开始 输出到日志
  12. //这里结束 输出到日志
  13. self::load404Page();
  14. $controller = new PageNotFindController();
  15. $controller->index();
  16. }
  17. }

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

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

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

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

其中load404Page()函数如下:

  1. private static function load404Page(){
  2. $controllerFile = APP_PATH . "user/controller/PageNotFindController.php";
  3. if(file_exists($controllerFile)){
  4. include $controllerFile;
  5. }
  6. }

PageNotFindController.php

  1. <?php
  2. namespace user\controller;
  3. use core\Controller;
  4. class PageNotFindController {
  5. protected $smarty;
  6. public function __construct(){
  7. if(!class_exists("Smarty")){
  8. include VENDOR_PATH . "smarty/Smarty.class.php";
  9. }
  10. $this->smarty = new \Smarty();
  11. $this->smarty->template_dir = APP_PATH . "user/view/";
  12. $this->smarty->compile_dir = RESOURCES_PATH . "views";
  13. }
  14. public function index(){
  15. $this->smarty->display("page404.html");
  16. }
  17. }

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

相关文章