need help with bad word filter

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
walshy
Forum Newbie
Posts: 3
Joined: Sat Dec 02, 2006 4:16 pm

need help with bad word filter

Post by walshy »

hi all. Im trying to implement a bad words filter to my guest book but im having prolems with it can someone help me try and sort it out please.
I think my problem is when i am accessing the text field to get my comments out to check. This is my code below which i have so far.

Code: Select all

<?php

$file = "gb.txt";
$open = fopen($file, "r")
	or die("txt file missing");
$size = filesize($file);
$fstring = fread($open,filesize($file)+1);

?>

<script language=javascript>

//checks to see if the domains are valid and @ sign is present


function emailCheck(emailAddress){

var domain = new Array('.com','.net','.ac','.co','.uk');
var eAdd = emailAddress;
var val = true;

var indexOfDot = eAdd.lastIndexOf(".");
var ext = eAdd.substring(indexOfDot,eAdd.length);
var atSignIndex = eAdd.indexOf("@");

if(indexOfDot > 5 && atSignIndex >1){
for(var i=0; i<domain.length; i++){
if(ext == domain[i]){
	val = true;
	break;
	}else{
		val = false;
	}
	}
	if(val == false){
		alert("Your Email Address "+eAdd+" is not correct");
			return false;
		}
					}else{
						alert("Your Email Address "+eAdd+" is not correct");
						return false;
						}
						return true;
}
</script>

<?
$comment = (commentForm.comment.value);
function BadWordFilter(&$comment, $replace)
{
	
	$bads = array (
		array("<span style='color:blue' title='I&#39;m naughty, are you naughty?'>smurf</span>","f***"),
		array("wank","w***"),
		array("<span style='color:blue' title='I&#39;m naughty, are you naughty?'>smurf</span>","s***")
	);

	if($replace==1) {								
		$remember = $comment;
		
		for($i=0;$i<sizeof($bads);$i++) {			
			$comment = eregi_replace($bads[$i][0],$bads[$i][1],$comment); 
		}

		if($remember!=$comment) return 1; 				
		
	} else {										
	
		for($i=0;$i<sizeof($bads);$i++) {			
			if(eregi($bads[$i][0],$comment)) return 1; 
		}	
		
	}
}


$any = BadWordFilter($wordsToFilter,1); 

$any = BadWordFilter($wordsToFilter,0); 

?>


    <form name=commentForm action="added.php" METHOD="POST" onSubmit="return BadWordFrilter(commentForm.comment.value)"  onSubmit="return emailCheck(commentForm.from.value)">
    Name *:
    <input type="text" name="name" size=20 maxlength="20">
    <br>
    <p><br>
      Email *:    
            <input type="text" name="from" size=27 maxlength="50" >
    </p>
    <p>&nbsp;</p>
      WebSite:
        <input type="text" name="webs" size=27 maxlength="50"></td>
        <div align="left"><br>
        Please add your comments<br>
       <textarea name="comment" rows=11 cols=55 wrap=physical></textarea>
       <br>
     </div><div align="left">
      <input type="submit" value="   Add   " >
    </div>
    </form>
Jon
User avatar
feyd
Neighborhood Spidermoddy
Posts: 31559
Joined: Mon Mar 29, 2004 3:24 pm
Location: Bothell, Washington, USA

Post by feyd »

I'm noticing several things
  • Two onsubmit attributes in your form
  • PHP code that's attempting to access a live Javascript value
  • Many HTML attribute values without quotes
Possible points of interest: file_get_contents(), isset(), preg_replace() and preg_match().

If you don't intend on using regular expressions fully str_ireplace() may be better.
walshy
Forum Newbie
Posts: 3
Joined: Sat Dec 02, 2006 4:16 pm

Post by walshy »

thanks feyd, im a noob to php really and i am still struggling to get to grips with how to actually do this and get it working.
ive removed the 2 on submit values but how would i call my function?

Jon
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

PHP is a server side language. That means PHP executes before the browser receives it.
JavaScript is a client side language. That means is executes only once the browser receives data from the server. The two cannot communicate directly.

Specifically, this is totally impossible:

Code: Select all

$comment = (commentForm.comment.value);
and is basically saying assign $comment to the concatenation of constants commentForm, comment and value. For example:

Code: Select all

define('commentForm', 'foo');
define('comment ', 'bar');
define('value', 'zim');
$comment = commentForm.comment.value;
echo $comment; // outputs: foobarzim
Equally:

Code: Select all

return BadWordFrilter(commentForm.comment.value)
is attempting to access a non-existant javascript function BadWordFrilter. If you fixed the typo, and called BadWordFilter instead, it still wouldn't work; that function doesn't exist on the client.
walshy
Forum Newbie
Posts: 3
Joined: Sat Dec 02, 2006 4:16 pm

Post by walshy »

thanks for the reply ole,
so how would i go about getting the value from my text box then to check against the words? sorry bout this like i said earlier im new to all this.

jon
User avatar
Ollie Saunders
DevNet Master
Posts: 3179
Joined: Tue May 24, 2005 6:01 pm
Location: UK

Post by Ollie Saunders »

Three methods:

Quickest and Easiest - check it once the form is submitted in PHP
Easy but not so quick - check it using JavaScript to check it on the client AND then PHP (the 'and' is very important for security) once submitted.
Less simple - use AJAX to send it to the server, whilst still ensuring a check is carried out on the server at the end.

I would recommend the first one if you can't do the third (mostly never worth doing) because the second has potential code maintenance issues. Anyway here's some nice guide code for validating forms:

Code: Select all

<?php
if (!empty($_POST)) {               
    $validationErrors = array();   // validate function below will change this
    /**
     * Validate a post field.
     *
     * @param string|int $field    index of $_POST to validate
     * @param callback $test       name of function to test with
     *                             function return used to determine if 
     *                             validation is sucessful
     * @param array $params        extra parameters to pass to function
     * @param string $error        error message to user if validation fails
     * @return bool                whether validation was successful
     */
    function validate($field, $test, array $params = array(), $error = '')
    {
        global $validationErrors;
        if (!isset($validationErrors)) { // in case someone forgets 
            $validationErrors = array();
        }
        // adds field value to parameter list
        $params = array_unshift($params, $_POST[$field]); 
        if (!$result = call_user_func_array($test, $params)) {
            $validationErrors[] = $error;
        }
        return $result;
    }
    /**
     * Example function for calling with validate
     *
     * @param string $value
     * @param int $length
     * @return bool
     */
    function exceedsLength($value, $length)
    {
        return strlen($value) <= $length; // EDIT: just corrected something here now
    }
    
    // This will call exceedsLength with parameters $_POST['foo'] and 30 and add
    // an error 'Foo is too long' if exceedsLength returns false
    validate('foo', 'exceedsLength', array(30), 'Foo is too long');
    // ctypealpha is an internal php function and requires no additional parameters
    validate('bar', 'ctypealpha', array(), 'Bar may only contain alphabetic characters');
    
    if ($numErrors = count($validationErrors)) {
        echo "There are $numErrors to correct";
        echo '<ul><li>' . implode('</li><li>', $validationErrors) . '</li></ul>';
    }
}
?>
<form action="#" method="post">
    <div class="field">
        <label for="foo">Foo</label>
        <input type="text" name="foo" id="foo" />
    </div>
    
    <div class="field">
        <label for="foo">Bar</label>
        <input type="text" name="bar" id="bar" />
    </div>
    
    <div class="field">
        <input type="submit" name="sub" id="sub" />
    </div>
</form>
I wrote that especially for you :)
Untested
Post Reply