Search code examples
phphtmlescaping

How to safely output HTML from a PHP program?


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

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

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

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.

In addition, variable values may contain angle brackets < and > that will interfere with HTML.

So how can we safely escape output for HTML?


Solution

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

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

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

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