-2

Let's say this code is executed after press the submit button in a form with purposes of sanitization:

<?php
$yourname = check_input(filter_input(INPUT_POST, 'yourname', FILTER_SANITIZE_STRING));
$email = check_input(filter_input(INPUT_POST, 'email', FILTER_SANITIZE_EMAIL));
$likeit = check_input(filter_input(INPUT_POST, 'likeit', FILTER_SANITIZE_STRING));
$comments = check_input(filter_input(INPUT_POST, 'comments', FILTER_SANITIZE_STRING));

function check_input($data) {
    $data = trim($data) . stripslashes($data) . htmlspecialchars($data);
    return $data;
}
?>

Taking in account that the filter_input function is being applied, is the check_input($data) function redundant in this case?

oxk4r
  • 452
  • 6
  • 17
  • I think this question belongs to [Code Review](https://codereview.stackexchange.com/) – Spoody Mar 03 '18 at 18:46
  • 1
    It's excessive and wrong! Understand what each of these functions like [stripslashes()](http://php.net/manual/en/function.stripslashes.php) and [htmlspecialchars()](http://php.net/manual/en/function.htmlspecialchars.php) actually does, and where it' appropriate to use it, rather than simply using throwing them into the function without understanding – Mark Baker Mar 03 '18 at 18:49
  • Context is good to know here, what do you intend to do with the collected data? – Progrock Mar 03 '18 at 18:52
  • Protecting form from hack and spam, of course – oxk4r Mar 03 '18 at 18:56
  • Sometimes filters don't perhaps act as you'd expect. `filter_var('foo(this is just a comment)@example.com', FILTER_SANITIZE_EMAIL);`, will break, what is, a valid address. – Progrock Mar 03 '18 at 19:09

1 Answers1

3

The current code of the check_input function is pretty useless: You get the input back concatenated 3 times but with different filters applied

function check_input($data) {
    $data = trim($data) . stripslashes($data) . htmlspecialchars($data);
    return $data;
}

Regarding filter_input(): Using FILTER_SANITIZE_STRING should be enough. From the documentation:

Strip tags, optionally strip or encode special characters.

This is basically what you intended with your own function.


Don't forget to watch out for SQL injection attacks. Using prepared statements as intended will keep you on the safe side.

rollstuhlfahrer
  • 3,988
  • 9
  • 25
  • 38