首页 > 解决方案 > 阻止 PHP 异常转义 html

问题描述

我有一个自定义异常类,例如:

class AwesomeException extends \Exception {

    public function __toString(){
        return "<strong>This is important!</strong>";
}

然后我throw new \AwesomeException("Blah blah"); & 而不是显示:

这个很重要!

粗体字,

输出包括:

<strong>This is Important!</strong>

当我查看源代码时,我看到:

&lt;strong&gt;This is Important!&lt;/strong&gt;

我尝试了覆盖getMessage(),但这是最终的,所以它不起作用。

我可以使用自定义输出进行全局尝试/捕获,例如:

try {
    //do all of the things
}
catch (\Exception $e){
    echo $e;
    echo $e->getTraceAsString();
}

但我真的很想用 htmlthrow $e打印原件__toString,而不是转义。我希望AwesomeException班级以某种方式强制执行这一点。

我也可以echo从我的内部 html __toString(),但这打破了预期__toString()

我在 PHP 7.4

编辑

我在想这可能是apache?我.htaccess的文件路径deliver.php,所以我把文件的开头写成:

<?php
ini_set('display_errors', 1); 
error_reporting(E_ALL);
class AwesomeException extends \Exception {
    
    public function __toString(){
        return "<strong>This is important!</strong>";
    }
}

throw new \AwesomeException();


echo 'done throwing';

exit;

我得到了输出源:

<br />
<b>Fatal error</b>:  Uncaught &lt;strong&gt;This is important!&lt;/strong&gt;
  thrown in <b>/path/to/file/deliver.php</b> on line <b>11</b><br />

标签: phpexception

解决方案


phpinfo()为“错误”、“异常”、“htmlentities”和其他几个运行了 ctrl+f 并最终找到了html_errors指令。

所以我:

ini_set('html_errors',0);

现在我的异常中的 html 正在以未转义的形式打印。不过,它不再加粗我的文件名或“致命错误”。


推荐阅读