I have a simple form that needs extra validation. I have an array of banned words, which if any are present, the form submission fails.
I’ve been able to get it to work if the only word in the input is banned. However if it contains normal words and a banned word, the form submission goes through.
I do know the banned words db is working fine, as I have test code to output all of them
This is what only works if a banned term is the only word/string in there.
// array of banned words to filter; comes from DB
$disallowed_terms = Array();
$disallowed = $ww_mysqli->prepare("SELECT * FROM nl_filters");
$disallowed->bind_param('s', $Filter);
$disallowed->execute();
$s_result = $disallowed->get_result();
// check each input for banned words
while ($row = $s_result->fetch_assoc()) {
$disallowed_terms[] = $row;
// only wrote this for $sprequests for testing
// strpos() doesn't seem to the right method here
$sprequests_check = strpos($sprequests,$disallowed);
if (in_array($sprequests_check,$row) !== false) {
// adding anything to $reasons will cause submission to fail
$reasons .= '|error';
}
if (in_array($theirname,$row) !== false) {
$reasons .= '|error';
}
if (in_array($email,$row) !== false) {
$reasons .= '|error';
}
if (in_array($phone,$row) !== false) {
$reasons .= '|error';
}
}
The current list of banned words is here
2
Answers
The soloution I came up with for this problem uses the $disallowed_terms array to create a regex pattern that is then used to check each term in a users input.
We can check each term by first removing any special characters from the input and replace it with a space and then using explode to sperate the string out into an array.
I simplified the code for the example so the $disallowed_terms is a static asrray and the inputs are also a static array. Feel free to modify the code to match your project.
I have left comments throughout the code explaining whats going on but if I missed something let me know :). See the code below:
The obvious limitation to this solution is it won’t be able to detect words like ‘cr*zy’ because it removes the * and replaces it with a space. On the flip side it will detect the word crazy in sting like this ‘.:thats-crazy:.’.
If some of the disallowed words contain special characters the solution may need modifaction as well. As the create_disallowed_terms_regex() function could break and words with special characters would never be detected because the solution strips special characters out of the input. Both issues can be mitigated with minor changes.
You can try this:
Use stripos() so the search is case-insensitive.
Use $row[‘filter’] assuming filter is the column name in the database, instead of $disallowed in the stripos check.
The function ‘containsBannedWord’ checks if any banned word is present in the input.