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

Viewed 389

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?

3 Answers

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 ?>'>
Related