开发者

Prevent HTML character codes from being rendered in textarea

Is it possible to display HTML character codes stored in a text field in SQL to a textarea without rendering them as 开发者_C百科their appropriate character? i wasnt & to show up as & (the way it's stored in the table). Or is their a way I should be storing the HTML so I won't need to worry about this?

(site is using PHP)


In PHP you can use the function htmlspecialchars ( http://php.net/manual/en/function.htmlspecialchars.php ):

<?php
$new = htmlspecialchars("<a href='test'>Test</a>", ENT_QUOTES);
echo $new;
?>

and it will render:

&lt;a href=&#039;test&#039;&gt;Test&lt;/a&gt;

if you want decode them back you just use the function htmlspecialchars_decode

<?php
$str = '<p>this -&gt; &quot;</p>';

echo htmlspecialchars_decode($str);

// note that here the quotes aren't converted
echo htmlspecialchars_decode($str, ENT_NOQUOTES);
?>


What you're talking about is called HTML Encoding; every modern language has a facility in its library for doing that, such as the htmlspecialchars function in PHP. For more PHP information, see this SO question.

You should also make sure that you're properly sanitizing the inputs, even against multiple rounds of HTML decoding; otherwise you'll be susceptible to CSS (Cross Site Scripting) attacks.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜