【问题标题】:WordPress Security Standards want me to escape my html, but how to do it correctly?WordPress 安全标准希望我转义我的 html,但如何正确地做到这一点?
【发布时间】:2021-08-09 09:24:20
【问题描述】:

我正在尝试构建一个自定义 Elementor 小部件 (https://developers.elementor.com/creating-a-new-widget/)。在 render() 函数中,我可以将正在渲染的 HTML 放在前端。

现在我建立了一个项目,它使用代码嗅探器来强制执行 wordpress 编码标准。

render() 函数的代码如下:

/**
 * Render widget output on the frontend
 */
protected function render() {
    $i_am                 = __( 'I am', 'hello-elementor-child' );
    $and_i_am_looking_for = __( 'and I am looking for', 'hello-elementor-child' );

    $output = <<<HTML
        <form>
            <div>
                <label>$i_am</label>
                <input type="text" name="i_am" value="" />
            </div>
            <div>
                <label>$and_i_am_looking_for</label>
                <input type="text" name="and_i_am_looking_for" value="" />
            </div>
        </form>
    HTML;

    echo $output;
}

CodeSniffer 现在抱怨 $output,因为我没有逃避它:

所有输出都应通过转义函数运行(请参阅 WordPress 开发人员手册中的安全部分),找到“$output”。

PHPCS(WordPress.Security.EscapeOutput.OutputNotEscaped)

现在查找 WP Dev Handbook,它告诉我几种转义输出的方法,而 esc_html for excamples 正是它应该做的,但是当然,然后我让前端向用户显示 html 代码呈现由浏览器呈现的实际 html...

那么在这个场景中,我如何取悦代码嗅探器,同时输出我需要的东西?

【问题讨论】:

  • 只有真正的来自用户输入的内容需要被转义(为了防止 XSS 攻击)。
  • 没错,但 wordpress 编码标准希望我逃避这一点。我知道我可以逐行回显并且只转义特定变量,但在这种情况下,我想使用 heredoc。在使用 heredoc 的情况下,codesniffer/wordpress 无法知道我可能包含哪些变量。所以我认为codesniffer的投诉是可以的。但是一定有办法解决吗?
  • 自动化编码标准并不总能理解您正在做的事情的完整背景。如果您对没有危险感到满意,您就不能忽略它(也许在代码中添加注释作为将来的注释)吗?
  • I know I could echo line by line and only escape specific variables, but in this case I would like to use heredoc...您仍然可以在连接变量之前对其进行转义。
  • 忽略它:在 javascript linters 中,我知道您可以添加 cmets 以忽略当前行或整个文件的某些规则,但在 PHP 中我不知道该怎么做。这个项目使用预提交钩子强制执行这些规则,只有在没有错误时才允许我提交结果:P

标签: php wordpress elementor codesniffer


【解决方案1】:

如果你想在 php.ini 中回显 html 代码。最好把它们做成String。 请像这样更改您的代码:

$output = "<HTML>
    <form>
        <div>
            <label>$i_am</label>
            <input type='text' name='i_am' value='' />
        </div>
        <div>
            <label>$and_i_am_looking_for</label>
            <input type='text' name='and_i_am_looking_for' value='' />
        </div>
    </form>
</HTML>";

【讨论】:

  • 这不是问题,因为我必须在最后回显 $output,这会触发 phpcs 抱怨 $output 没有被转义。
猜你喜欢
  • 2020-02-16
  • 2019-05-18
  • 2016-01-13
  • 2014-02-08
  • 1970-01-01
  • 1970-01-01
  • 2011-07-17
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多