Search code examples
phphtmlmysqlhtml-entitiesmysql-real-escape-string

Escaping HTML for MySQL whilst retaining valid HTML structure


I have user content entered through a basic HTML editor. I need to validate this content and insert it safely into a MySQL database without changing its format.

Say my user content is:

$usercontent = "<p>This is my content</p>";

If I use:

mysql_real_escape_string($usercontent);

I get this inserted into the database:

%3Cp%3EThis+is+my+content%3C%2Fp%3E

But I want the literal HTML inserted instead:

<p>This is my content</p>

Is there a simple way I can convert the mysql_real_escape_string modified content back into normal HTML?

I should let it be known that I am modifying an already-written web app and I am not being paid to rewrite the entire thing - it's a quick debug I'm doing. Therefore I really do need to do it this way - I really need to store normal HTML in the database, just making sure I've validated the best I can before doing so. This also excludes combing through the entire app implementing PDO as an option too.

I've done some digging and I can't find an answer to this question... at least not explicitly... and anything on the subject seems to be wrapped up in lectures. Assuming I've read these lectures is there a simple short answer to this problem?

EDIT

It turns out my strange encoding was happening elsewhere and wasn't caused by mysql_real_escape_string at all. This makes my issue very unique to my situation and probably not much help to anybody. However, urldecode did indeed solve my problem.


Solution

  • Use urldecode to get proper HTML