0

Is there a generic way to prevent XSS on a form?

Is we consider the basic sample code below...

HTML:

<form action="test.php" method="POST">
 <input type="text" name="test">
</form>

PHP:

function new_test($test) {
    array_walk($test, 'array_sanitise');

    $fields = '`' . implode('`, `', array_keys($test)) . '`';
    $data = '\'' . implode('\', \'', $test) . '\'';

    $query = mysql_query("INSERT INTO `test` ($fields) VALUES ($data)");
    if (!$query) {
       die('Could not query:' . mysql_error());
    }
}

$test = array(
  'test'     => $_POST['test']
);

new_test($test);

Is this enough to protect from SQL injections & XSS breaches? Is there a better way to do it? Or is there no generic way?

Alex
  • 89
  • 1
  • 1
  • 4
  • Whenever you need to ask more than one question, it is likely that your question is too broad. Closed against a PHP XSS reference question. For sql injection please educate yourself on http://bobby-tables.com/ - And yes your code is prone to SQL injection. [How can I prevent SQL-injection in PHP?](http://stackoverflow.com/q/60174/367456) – hakre Dec 27 '14 at 10:48
  • mysql_ functions are deprecated, please use [mysqli](http://php.net/manual/en/book.mysqli.php) or [PDO](http://php.net/manual/tr/book.pdo.php) instead of mysql_ functions. – salep Dec 27 '14 at 20:39

1 Answers1

2
  1. Against SQL injection you should escape everything user input used in sql queries. Or use prepared statements/bind variables. Escaping: http://uk1.php.net/mysqli.real-escape-string.php, PDO: http://php.net/manual/en/ref.pdo-mysql.php
  2. Against XSS, you have to escape what you display to your client. But this depends on what and where you display. You have to use different escaping in html
    • between tags,
    • in tag attributes
    • in css
    • in javascript
    • ...

You can read more about the different methods of XSS here: https://www.owasp.org/index.php/XSS_Filter_Evasion_Cheat_Sheet

I see you used only array_sanitise whose code isn't added to the question, so it is hard to say what is it. But based on its usage it seems to be some kind of SQL escaping, so hopefully it helps to defend against SQL injections. Hopefully.

Mouser
  • 13,132
  • 3
  • 28
  • 54
Lajos Veres
  • 13,595
  • 7
  • 43
  • 56
  • Thanks! function array_sanitise(&$item) { $item = htmlentities(strip_tags(mysql_real_escape_string($item))); } – Alex Dec 27 '14 at 10:49