In PHP, I've always used this to represent inputs and textareas:

$foo = trim(htmlentities($_POST['foo'], ENT_QUOTES); // the trim is to prevent empty submissions

Can it also be valid to prevent SQL injection attacks?

  • The answer to your SQLi question is no.
    – h4ckNinja
    May 17, 2016 at 4:27
  • 1
    We need context. Where is $foo being used? Using htmlentities might be undesirable in this context depending on what you're doing with the user-provided data.
    – Dai
    May 17, 2016 at 4:31
  • 1
    The headline and the tags read "XSS" (Cross-Site-Scripting), the question body "SQL injection". These are two different things. Which one is it you are asking about?
    – Philipp
    May 17, 2016 at 7:00
  • The SQLI was intended as just an optional question
    – Slim Shady
    May 17, 2016 at 13:38
  • @BenJunior when asking questions, please be more clear about what your main question is and make sure your title and body are in alignment.
    – schroeder
    May 17, 2016 at 14:40

1 Answer 1


Your sql statement:

 select * from foo where numerical_id=$foo;

The POST request


The resulting value in $foo

 foo=1;drop table foobar;

The resulting SQL statement

 select * from foo where numerical_id=foo=1;drop table foobar;

Can it also be valid to prevent SQLIs?

Obviously no.

As for the XSS: Your PHP:

$foo = trim(htmlentities($_POST['foo'], ENT_QUOTES));
print "<script>numerical_id=$foo;</script>"

The POST request


The result


Since you cannot use quotes in ... you can construct your strings with String.fromCharCode or similar, so no need to give a quoted string.

Can this prevent XSS?

Obviously also no, at least not general XSS.

In general: Different context has different escaping rules. htmlentities is useful for HTML context, but not for URL context, JS context, CSS context, SQL context ... . And it gets more complex, like dynamically adding code to an onclick attribute has both HTML and JS context.


You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .