Search code examples
phpif-statementsanitization

Sanitizing data PHP - do i need to escape user inputs that are inside if statements?


I'm sanitizing all user inputs that are output on page, e.g.:

echo escape($user_input);

I have a question about user inputs that are not output to the page but are inside statements - do they need escaped?

Is this OK:

if ($user_input == 'something') { echo escape($another_user_input); }

or should it be:

if (escape($user_input) == 'something') { echo escape($another_user_input); }

Same question for other logic (foreach loops etc.) which would add more faff than this simple example.


Solution

  • The only reason you ever need to escape something is when you're interpolating data into another text medium which gets re-interpreted according to some rules.

    E.g.:

    echo '<p>' . $somedata . '</p>';
    

    This is programmatically generating HTML which will get interpreted by an HTML parser and will have specific behaviour depending on what's inside $somedata.

    $query = 'SELECT foo FROM bar WHERE baz = ' . $somedata;
    

    This is programmatically generating an SQL query which will get interpreted by an SQL parser and will have specific behaviour depending on what's inside $somedata.

    If you want to ensure that HTML or that query behaves as you intended, you better make sure you generate those textual commands in a way does that not allow anyone to inject unwanted commands.

    if ($somedata == 'something')
    

    Here you're not creating some new text which will be interpreted by something. There's no way for anyone to inject anything here. It's not like PHP is replacing $somedata with the contents of $somedata and then re-interprets that line with the interpolated data. So there's no need to escape this in any way.

    Also see The Great Escapism (Or: What You Need To Know To Work With Text Within Text).