简体   繁体   中英

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

I am using unescaped data for example 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?

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.

It looks like this:

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

Then I can simply run it like this: 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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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