0

I know that many people believe it is wrong to edit Superglobals in PHP. But I found myself to always trim user input in every controller of my webapp. To solve the problem once and for all I now just trim all values of these Superglobals like that:

# trim ALL inputs
foreach ($_REQUEST as $key => $value) {
    $_REQUEST[$key] = trim($value);
}
foreach ($_COOKIE as $key => $value) {
    $_COOKIE[$key] = trim($value);
}
foreach ($_GET as $key => $value) {
    $_GET[$key] = trim($value);
}
foreach ($_POST as $key => $value) {
    $_POST[$key] = trim($value);
}

Some users might want to define a password that starts or ends with a whitespace. Apart from that I cannot think of any usecase where trimming might do any harm.

Has anybody else tried to trim these Superglobals and ran into strange side effects that I should be aware of?

Pascal Klein
  • 23,665
  • 24
  • 82
  • 119
  • You shouldn't keep RAW user password ANYWHERE, especially in cookies. – Luke Feb 28 '17 at 11:15
  • Basicly do not OVERRIDE any off `$_` variables. Use a copy and then only work with the copy. Else there is `filter_input` http://php.net/manual/en/function.filter-input.php and filter http://php.net/manual/en/filter.filters.php Whatever, useing `trim` is ok at this point. – JustOnUnderMillions Feb 28 '17 at 11:16
  • Not sure it is a good idea to use $_REQUEST anyway. see: [What's wrong with using $_REQUEST?](http://stackoverflow.com/questions/2142497/whats-wrong-with-using-request) – Ryan Vincent Feb 28 '17 at 11:16
  • @Luke: I am not keeping the password in cookies. But when the users inputs his password to signup or login, the password is obviously in $_POST and $_REQUEST. – Pascal Klein Feb 28 '17 at 11:22
  • @Ryan: Yes it is often a good idea to use $_REQUEST. That is also what the first answer (of the question you linked) says: "There's absolutely nothing wrong with taking input from both $_GET and $_POST in a combined way." – Pascal Klein Feb 28 '17 at 11:23
  • That isn't the issue with $_REQUEST - it is the fact that sometimes $_COOKIE can clobber one of the $_GET or $_POST values. It happens ;-/ – Ryan Vincent Feb 28 '17 at 11:33
  • 1
    It all depends on your needs. On a site like this if you trimmed all the data some code block formatting would break because the indentations would be lost. – chris85 Feb 28 '17 at 11:41

0 Answers0