views:

94

answers:

2

Is it possible to display HTML character codes stored in a text field in SQL to a textarea without rendering them as 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)

+1  A: 

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);
?>
Garis Suero
Thanks, I had actually figured this out a few minutes after I posted the question, but thanks for the response.
Bruack
A: 

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.

Ian Varley