Always an invalid username with / without bad words

I am trying to write code that negates any username that contains bad words. No matter what I do, I get an "Invalid username".

$f = @fopen("censor.txt", "r");

$bw = fread($f, filesize("censor.txt"));
$banned_words = explode("\n", $bw);

function teststringforbadwords($wantusername, $banned_words)
{
    foreach ($banned_words as $banned_word) {
        if (stristr($wantusername, $banned_word)) {
            return FALSE;
        }
    }
    return TRUE;
}

if (!teststringforbadwords($wantusername, $banned_words)) {
    echo 'string is clean';
} else {
    echo('string contains banned words');
    $message = "Invalid username.";
}

@fclose($f);

I am currently studying php and have tried everything I can think of to make it work - help!

+4
source share
1 answer

The function works fine, but you call it incorrectly, because the function returns Falseif the word is incorrect, if it matches:

if( teststringforbadwords( $wantusername, $banned_words ) )
{
    echo 'string is clean';
}
else
{
    echo('string contains banned words');
    $message = "Invalid username.";
}

Otherwise, if you want to maintain consistency with the function name, you must invert Trueand Falsereturn the internal function.

+8

Source: https://habr.com/ru/post/1629039/


All Articles