简体   繁体   中英

PHP contact form detect words in a text field

I have a contact form with a text field for people to enter the name of their company/organization. I want to prevent the form from being submitted if it contains any or variation of any the following words,: uc, uci, irvine, ucirvine. Here is my script:

// company group
    if(trim($_POST['cmpnyGrp']) === '') {
        $cmpnyGrpError = '<span class="error">Please enter your company or group name.</span>';
        $hasError = true;
    } else if (isset($_POST['cmpnyGrp'])) {
        $banned = array('uci', 'uc', 'ucirvine', 'uc-', 'uc ', 'irvine');
        $cmpnyGrpError = '<span class="error">If you are UCI, select UC under User Type and enter account string.</span>';
        $hasError = true;
    } else {
        $cmpnyGrp = trim($_POST['cmpnyGrp']);
    }

I know I am doing something wrong because this isn't working. Im not a programmer, but I am doing my best to try to understand what to do. Any assistance would be greatly appreciated. Thank you very much.

Right now, you initialize $banned and then never use it. You need an if(in_array($_POST['cmpnyGrp'], $banned) {...} . This will check whether the value of cmpnyGrp is in the array of banned words. However, note that such a form of blacklisting can never check for each possible variation of "uc".

You're declaring an array of banned words but doing nothing with it. You need to use it something like as follows:

foreach ($banned as $b) {
    if (strpos($_POST['cmpnyGrp'], $b) !== false) {
        $cmpnyGrpError = '<span class="error">If you are UCI, select UC under User Type and enter account string.</span>';
        $hasError = true;
        break;
    }
}

if (!isset($hasError)) {
    $cmpnyGrp = trim($_POST['cmpnyGrp']);
}

Try this:

if(trim($_POST['cmpnyGrp']) === '') {
    $cmpnyGrpError = '<span class="error">Please enter your company or group name.</span>';
    $hasError = true;
} else {
    $banned = array('uci', 'uc', 'ucirvine', 'uc-', 'uc ', 'irvine');
    $found = false;
    foreach ($banned as $b) {
        if (stripos($_POST['cmpnyGrp'], $b)) {
            $found = true;
            break; // no need to continue looping, we found one match
        }
    }
    if ($found) {
        $cmpnyGrpError = '<span class="error">If you are UCI, select UC under User Type and enter account string.</span>';
        $hasError = true;
    } else {
        $cmpnyGrp = trim($_POST['cmpnyGrp']);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM