2

I already followed the suggestion here and added:

/* Prevent XSS input */
$_GET   = filter_input_array(INPUT_GET, FILTER_SANITIZE_STRING);
$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

to the top of my PHP file. But my question is, is the way I use the $_POST on this required input secure?

if (empty($_POST['number']) || !isset($_POST['number'])) {
    $this->setStatusMessage($translator->translate('please enter your number.'));
    $this->setStatus(KDatabase::STATUS_FAILED);

    return false;
}else{
    $this->telefonnummer = $_POST['number'];
}
4
  • Why are you using a suggestion with 1 vote instead of the one with 209 votes? The correct method to prevent XSS in html is to use htmlspecialchars on output, but you should look at OWASP's XSS cheat sheet if you plan on inserting user supplied values anywhere else. Mar 11, 2018 at 0:09
  • If you're expecting a number, you can validate if it is numeric. Also, you didn't give use any output context, so while that filter might work for most cases, it doesn't catch all.
    – Arminius
    Mar 11, 2018 at 0:14
  • @AndrolGenhald Because OP is sorting answers active-first. :-)
    – Arminius
    Mar 11, 2018 at 0:15
  • @Arminius Wow...I had no idea that was possible. That's actually really useful. Mar 11, 2018 at 0:17

1 Answer 1

2

Don't think about protecting your inputs to prevent XSS - it should all be about output.

XSS, and other code injection vulnerabilities happen when data is not properly escaped or converted for the context in which it will be used.

How you do that depends on the output technology and context. As AndrolGenhald mentioned in the comments, if you are outputting directly from PHP, without using a templating library, and you want to use a variable in the context of HTML code, then you should pass it through the htmlspecialchars function. With other contexts and technologies the answer will be different. You need to find the correct way to escape data for each context.

If you can make sure you're always escaping data on output correctly, then you shouldn't use FILTER_SANITIZE_STRING. That irreversibly strips various things out of the string, rather than simply making them safe. On a well made website like StackExchange I'm free to submit the code <script>alert('XSS')</script>, and it doesn't get stripped, it just gets encoded so the browser safely displays it instead of executing it.

The code in your question doesn't include any output, so it can't itself be vulnerable to XSS. You need to show code that produces some output if you want to know if it does it safely.

You must log in to answer this question.