64

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?

miken32
  • 42,008
  • 16
  • 111
  • 154
user198729
  • 61,774
  • 108
  • 250
  • 348

3 Answers3

108

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.

Dominic Rodger
  • 97,747
  • 36
  • 197
  • 212
  • 2
    Confirmed with html5 specs here: http://stackoverflow.com/questions/5320177/what-values-can-i-put-in-an-html-attribute-value – e-motiv Jan 31 '14 at 23:46
  • 1
    +1 for mentioning "ENT_QUOTES". I was already using the this function but double quotes would mess up the html. – danielson317 Aug 17 '17 at 16:55
  • Note that ENT_QUOTES will still cause errors in javascript within html: link Use addslashes first and then htmlspecialchars to fix this issue. – Leigh Bicknell Mar 14 '19 at 11:27
  • @LeighBicknell I think it is better to do `htmlspecialchars(json_encode($variable), ENT_QUOTES)`. I haven't tested it in your particular example, but I think it should work nicely for any type of value. – frodeborli Mar 25 '21 at 12:11
  • Since PHP8.1 `ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401` is the default value. – Tobias K. Nov 28 '22 at 14:50
3

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

Pay attention to the second parameter of that function.

Crozin
  • 43,890
  • 13
  • 88
  • 135
-1

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

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

ling
  • 9,545
  • 4
  • 52
  • 49