-1

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 '16 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. – The D May 17 '16 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 '16 at 7:00
  • The SQLI was intended as just an optional question – Slim Shady May 17 '16 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 '16 at 14:40
4

Your sql statement:

 select * from foo where numerical_id=$foo;

The POST request

 foo=1;drop%20table%20foobar;

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:

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

The POST request

foo=10;document.write(...)

The result

<script>numerical_id=10;document.write(...)</script>

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.