66

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, it should be changed 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?

3 Answers 3

112

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.

Sign up to request clarification or add additional context in comments.

5 Comments

Confirmed with html5 specs here: stackoverflow.com/questions/5320177/…
+1 for mentioning "ENT_QUOTES". I was already using the this function but double quotes would mess up the html.
Note that ENT_QUOTES will still cause errors in javascript within html: <a onclick="$.fancybox.open('<php echo htmlspecialchars($variable_with_single_quote, ENT_QUOTES); ?>')">link</a> Use addslashes first and then htmlspecialchars to fix this issue.
@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.
Since PHP8.1 ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401 is the default value.
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:

 int $flags = ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401,

Comments

-2

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.