通过 PHP 设置 html 属性的最佳实践是什么?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2109583/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 05:03:33  来源:igfitidea点击:

What's the best practice to set html attribute via PHP?

phphtml

提问by user198729

When doing this job in PHP,one may meet this kind of issue:

在 PHP 中做这项工作时,可能会遇到这样的问题:

<span title="<?php echo $variable;?>">...

The problem is that if $variablecontains double quotes,should change it to \"

问题是如果$variable包含双引号,应该将其更改为\"

And that's not the whole story yet:

这还不是全部:

<span title='<?php echo $variable;?>'>...

In this case,we need to change single quotes to \',but leave double quotes as is.

在这种情况下,我们需要将单引号更改为\',但保留双引号。

So how can we do it in a general property manner?

那么我们如何才能以一般的财产方式做到这一点呢?

回答by Dominic Rodger

You always want to HTML-encode things inside HTML attributes, which you can do with htmlspecialchars:

您总是希望对 HTML 属性中的内容进行 HTML 编码,您可以使用以下方法htmlspecialchars

<span title="<?php echo htmlspecialchars($variable); ?>">

You probably want to set the second parameter ($quote_style) to ENT_QUOTES.

您可能希望将第二个参数 ( $quote_style) 设置为ENT_QUOTES

The only potential risk is that $variablemay already be encoded, so you maywant to set the last parameter ($double_encode) to false.

唯一的潜在风险是它$variable可能已经被编码,因此您可能需要将最后一个参数 ( $double_encode) 设置为false

回答by Crozin

Well, before you output any text into HTML you should escape it using htmlspecialchars(). So just make sure (double) quote is correctly changed.

好吧,在将任何文本输出到 HTML 之前,您应该使用htmlspecialchars()对其进行转义。所以只需确保(双)引号正确更改。

Pay attention to the second parameter of that function.

注意该函数的第二个参数。

回答by Boldewyn

To address your edit [Edit:that you have removed meanwhile]: When you place dynamically JavaScript onto your site, you should beforeknow quite well, what it would look like. Else you open the door widely for XSS attacks. That doesn't mean you have to know every quotation mark, but you should know enough to decide how to embed it at the line where you finally output it in the HTML file.

为了解决您的编辑[编辑:您已删除与此同时]:当您将动态的JavaScript到你的网站,你应该之前一清二楚,它会是什么样子。否则你就会为 XSS 攻击打开大门。这并不意味着您必须知道每个引号,但您应该知道如何将其嵌入到最终将其输出到 HTML 文件的行中。

Beyond that,

除此之外,

<a onclick="func(&apos;l&apos;)">

works exactly like

完全一样

<a onclick="func('l')">

回答by ling

The Bat tool has a StringTool::htmlAttributes ( $arrayOfAttributes ) method that does the job too.

Bat 工具有一个 StringTool::htmlAttributes ( $arrayOfAttributes ) 方法也可以完成这项工作。

https://github.com/lingtalfi/Bat/blob/master/StringTool.php

https://github.com/lingtalfi/Bat/blob/master/StringTool.php