The forums ran from 2008-2020 and are now closed and viewable here as an archive.

Home Forums Back End php variables Reply To: php variables


i heard doing html special chars prevent sql injection was i wrong?

Yes, this is completely wrong.

The function name gives you a big clue. htmlspecialchars is for escaping data for use in HTML, not SQL. When you echo something to your HTML webpage, but you want to make sure it displays as text, use htmlspecialchars. For example:


// I want to have a paragraph that talks about <script> tags.
$script = "<script>alert( 'hello, html injection!' );</script>";

// but if I do this…
echo "<p>$script<p>";
// I'll get an _actual_ script tag.

// if I do this…
echo "<p>".htmlspecialchars( $script )."</p>";
// I'll get what I want: _text_, not javascript.

But, even though it’s not meant for sql injection, will it work? No. Read the documentation: the default flags for handling conversions is ENT_COMPAT.

  • ENT_COMPAT Will convert double-quotes and leave single-quotes alone.
  • “‘” (single quote) becomes & #39; (or &apos;) only when ENT_QUOTES is set.

[emphasis added]

This means that the one character you definitely always must escape in SQL queries is going through untouched.

Besides that, even if it did encode your single quotes, that’s not the same as escaping them. Your database doesn’t handle HTML encoding: it will store the entity code, not the character it is meant to represent: this means your data will be corrupted.

I use database wrapper class that uses pdo..

This class has a method named run. If you look at the source code, you’ll see that it actually uses prepared statements, which is good. If you ever use this function directly, however, you need to make sure that you never put data in the $sql parameter that came from the user, as this will prevent it from being escaped. Any data that came from the user needs to go in the $bind parameter.