Htmlspecialchars() Doesn't Want to Convert

This seems like it should be a no brainer but I’m completely stumped. I have a textarea in a form (POST) as an input. Upon processing the submission of that form I have this:

$HTML = htmlspecialchars($_POST['HTML'], ENT_QUOTES);

The problem is that when I echo $HTML out, nothing is actually replaced.

INPUT: This is to ‘correct’ the errors.
OUTPUT: This is to ‘correct’ the errors.

Am I missing something in my syntax? I don’t see any errors so I have absolutely no idea where to go from here.


Look at the HTML source, not the HTML being displayed by your browser.

The PHP error log (just found) shows:

[19-Mar-2010 14:53:44] PHP Notice: Undefined index: HTML in /home/… on line 14

What does undefined index mean?

[19-Mar-2010 14:53:44] PHP Notice: Undefined index: HTML in /home/… on line 14

What does undefined index mean?

You do not have a form element named ‘HTML’ posting to this script. :wink:

However, if you are receiving the output mentioned in your earlier post, try wrapping the encoded string in var_dump(). Chances are, what ever you’re viewing the source with is encoding it back.

A quick sanity check says it should work Ok Jeff.

echo htmlentities(
    "Well, hello y'all.",
); # Well, hello y& #039;all.

Clearly I’m either an idiot or haven’t had enough coffee yet. I’m going to hope it’s the latter. Didn’t even occur to me that the browser would display it differently. :rolleyes:

Well it’s working, so I’m not going to freak out about this but it’s interesting. I really do have a form element posting because that’s I can see the value of the variable and can also (thanks fo AlienDev) insert it into the database.

If you are using htmlspecialchars() to escape the HTML so your SQL doesn’t invalidate, there is still a security risk.

You should use mysql_real_escape_string() (or the one for your database server) instead :slight_smile:

You’re a genius. From the 20 seconds I spent reading about mysql_real_escape_string() it looks like it doesn’t actually escape the same characters as htmlspecialchars() does - is that right? It seems messy to use both functions.

Right. htmlspecialchars() will escape <> characters to <> (and quotes to &quote; if you tell it to). mysql_real_escape_string() escapes ’ to ‘’. Double-single-quotes (does that make sense?) is how SQL escapes characters.

htmlspecialchars escapes for HTML, what will hurt HTML will not hurt SQL. However what doesn’t hurt HTML will hurt SQL.

HTML_escape is for output to HTML
SQL_escape is for output to SQL

Thank you to each of you for lighting fast responses and refraining from calling me out on my obvious errors. You would think that after 7 years I would have figured some of these basic things out by now. :smiley:

Point taken. Time to go secure the SQL queries and then moving on to bacon doughnuts. Anthony, I know you’re jealous but they won’t do well via airmail.