简体   繁体   English

我可以让 php 在使用时自动转义 HTML 字符吗<!--?= ?--> ?

[英]Can I make php automatically escape HTML chars when using <?= ?>?

I am using unescaped data for example some string " <>> ' blah .我正在使用未转义的数据,例如some string " <>> ' blah

This causes trouble when I do this:当我这样做时,这会导致麻烦:

<input value="<?= $my_string ?>">

Which results in:结果是:

<input value="some string " <>> ' blah">

Is there a way to tell php to call htmlspecialchars on everything before printing it to the html document using <?=?> so I don't have to call it manually every time?有没有办法告诉 php 在使用<?=?>将其打印到 html 文档之前对所有内容调用htmlspecialchars ,这样我就不必每次都手动调用它?

No, this is not possible.不,这是不可能的。 But you could make a shortcut method that.但是你可以做一个快捷的方法。 For example like this:例如像这样:

function h($string){
     return htmlspecialchars($string);
}

What I do on my website is that I have a premade function that I call whenever I am echo'ing something on either a profile or anywhere.我在我的网站上所做的是,我有一个预制的 function,每当我在个人资料或任何地方呼应某些东西时,我都会调用它。

It looks like this:它看起来像这样:

function text_convert($txt){
     return htmlspecialchars($txt);
}

Then I can simply run it like this: echo text_convert($string);然后我可以像这样简单地运行它: echo text_convert($string);

There are a number of ways of dealing with it, just using single quotes in the HTML is the quickest and dirtiest:有多种处理方法,仅在 HTML 中使用单引号是最快和最脏的:

<input value='<?= $my_string ?>'>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM