PDA

View Full Version : PERL To PHP Conversion Help Please!


Layla
2006.06.29, 03:33 AM
Hello,

I am putting together a PHP script. While the script is now working great, one feature it is lacking, is a bad words filter. I am NOT an experienced PERL or PHP programmer, so I would very much appreciate it if someone here would be willing to convert the following small junk of code from PERL to PHP for me. I actually removed the real bad words and just put "badword1", "badword2", etc., for the sake of posting on this form. :)

<----- PERL Code Chunk Follows ----->

# The @badwords array contains the list of "bad words" that you want to prevent
@badwords = ("badword1", "badword2", "badword3", "badword4", "badword5");
sub check_badwords {
$badwords="off";
@check_fields = ("comments");
foreach $badword (@badwords) {
foreach $check_field (@check_fields) {
if ($FORM{$check_field} =~ /$badword/) {
$badwords="on";
}
}
}
if ($badwords eq "on") {
&badwords_error;
exit;
}
}

sub badwords_error {
print "Content-type: text/html\n\n";
print "<html><head><title>ERROR: Bad Words Found!</title></head>\n";
print "<body bgcolor=#FFFFFF text=#000000>";
print "<center><h1>Bad Words Found!</h1></center>\n";
print "Please keep our website wholesome and clean by refraining from using vulgar words!";
print "</form></body></html>\n";
}


<----- End Of PERL Code ----->

I also need to ask: once this code is converted to PHP, should I place it right before the "Submit" button in the actual PHP form on the HTML page, or does it need to go in the .php document itself, which is pointed to in the "requires" string, which is located at the top of the HTML form page?

Finally, if I understand the above code correctly, it doesn't replace the bad words with asterisks, or anything; it simply prevents the poster from sending their message altogether, right?

What if I wanted to replace the bad words, and then go ahead and let the message pass?

Thanks to whoever is able to help with this,

Layla

Zanathel
2006.07.16, 11:24 AM
global $gBadwords = array("badword1", "badword2", "badword3" /* ... */);

function checkBadwords($str)
{
$error = false;
foreach ($gBadwords as $word)
{
if (strpos($str, $word) !== false)
{
$error = true;
break;
}
}
if ($error)
{
warningFunctionSomething();
exit;
}
}

$formValue = $_POST["myMessage"];

checkBadwords($formValue);
That's it! But if you'll ask me to do it, i'd probably made the function to return a boolean value:
global $gBadwords = array("badword1", "badword2", "badword3" /* ... */);

function checkBadwords($str)
{
$error = false;
foreach ($gBadwords as $word)
{
if (strpos($str, $word) !== false)
{
$error = true;
break;
}
}
return $error;
}

$formValue = $_POST["myMessage"];

if (checkBadwords($formValue))
{
echo "Bad words found!";
exit;
}

// ... do stuff

The script is to be located in the script processing the clients form values.
You could though make a simple replace once the message is displayed.