0

I'm making a filter of Badword that return true if their is a bad word in a string. but what happen is that whatever the user write the code return false.

I already tried to convert the arguments of stripos() to string (just in case) but still. I tried preg_match() with "/$word/i", $_POST['message']

here is my function for the checking:

function MessageBad(){
    $BadWord = false;
    $bannedwords = file("bannedwords");
    foreach($bannedwords as $word) {
            if(stripos($_POST['message'], $word) !== false){
                    $BadWord = true;
            }
    }
    return $BadWord; 
}

but stripos($_POST['message'], $word) !== false always return false even when I enter only a badword from the bannedwods list...

Mahabubul Hasan
  • 1,396
  • 13
  • 20
Rzdhop
  • 37
  • 9
  • 2
    You might need some echo/log lines here to see what's going on. Between your foreach and if, try `echo "Does {$_POST['message']} contain $word? ".(stripos($_POST['message'], $word))."\n";` – aynber Feb 12 '20 at 19:21
  • what does `print_r($bannedwords)` give you? – Martin Feb 12 '20 at 19:22

1 Answers1

3

By default, the strings returned by file() include the newline character at the end of each line. So $word ends with a newline, and will only match if the bad word is at the end of the line.

Use the FILE_IGNORE_NEW_LINES flag to remove the newlines.

$bannedwords = file("bannedwords", FILE_IGNORE_NEW_LINES);

You should also break out of the loop once you find a match, there's no need to keep checking other words.

Barmar
  • 741,623
  • 53
  • 500
  • 612