phpstrpos

strpos() == true doesn't reliably give the correct result


Am not sure if the strpos() is the right function to use for this task.

PROBLEM:

if the user input hate or another string in my spam variable it return the spam filter message which is correct, but if the user input a spam variable mixed with any string not in the various it passes for processing.

I want the input to to check from the first string to the last string and that t doesn't contains any of the spam variable string then return process, here is my code

<?php
    //messgae
    error_reporting(E_ALL ^ E_NOTICE);
    $msg = array(); 
    $spam = "hate partisan party kill maim murder violence love sex fight beat assasinate thug steal sell bribe protest baricade bullets militia fear ";
    $spam_array = explode(" ",$spam);

    $check = strpos($spam, $_POST['message']);

         if ($check == true) {
        //do nothing
        $msg['invalid'] =  'Spam filter test didnt allow your message';

       } else {

        $msg['valid'] = 'process';   
       }


    if(isset($_POST['send'])){

      $message= $_POST['message']; 
    }

     ?>
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Strpos</title>
    </head>

    <body>
    <?php 
    if (isset($msg)) {
    echo '<ul>';
    foreach ($msg as $alert) {
    echo "<li class='warning'>$alert</li>\n";
    }
    echo '</ul>';
    }?>
    <form action="" method="post">
    <input name="message" type="text" />
    <input name="send" type="submit" value="Submit" id="send" />
    </form>
    </body>
    </html>

Solution

  • You started something there, with the $spam_array. They you check it know, you check if the exact string of bad words are found in your message.

    Also stripos instead of strpos so that it will be case insensitive.

    $spam = "hate partisan party kill maim murder violence love sex fight beat assasinate thug steal sell bribe protest baricade bullets militia fear ";
    $spam_array = explode(" ",$spam);
    $isSpam = isSpam($_POST['message'], $spam_array);
    
    
    function isSpam($content, $spamList)
    {
        foreach($spamList as $badWord) {
            if(stripos($content, $badWord) !== false) {
                return true;
            }
        }
    
        return false;
    }