What's the best practice to set html attribute via PHP?

PhpHtml

Php Problem Overview


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.

So how can we do it in a general property manner?

Php Solutions


Solution 1 - Php

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.

Solution 2 - Php

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.

Solution 3 - Php

To address your edit [Edit: that you have removed meanwhile]: When you place dynamically JavaScript onto your site, you should before know quite well, what it would look like. Else you open the door widely for XSS attacks. That doesn't mean you have to know every quotation mark, but you should know enough to decide how to embed it at the line where you finally output it in the HTML file.

Beyond that,

<a onclick="func(&apos;l&apos;)">

works exactly like

<a onclick="func('l')">

Solution 4 - Php

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

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser198729View Question on Stackoverflow
Solution 1 - PhpDominic RodgerView Answer on Stackoverflow
Solution 2 - PhpCrozinView Answer on Stackoverflow
Solution 3 - PhpBoldewynView Answer on Stackoverflow
Solution 4 - PhplingView Answer on Stackoverflow