Search code examples
phpcomparison-operators

PHP if value is null, send email


I have a PHP script handling a form, but I want to send a specific confirmation email if the user has entered any info for a specific set of fields (referral_1, referral_2, etc.)

Right now I have this to check if the user entered any info in the referral fields (text inputs):

if($referral_1 or $referral_2 or $referral_3 or $referral_4 or $referral_5 == null) {
    $autosubject = stripslashes($autosubject);
    $automessage = stripslashes($automessage);
    mail($email,"$autosubject","$automessage","From: $recipientname <$recipientemail>");
}

if($referral_1 or $referral_2 or $referral_3 or $referral_4 or $referral_5 != null) {
    $autosubject = stripslashes($autosubject);
    $automessage = stripslashes($automessage);
    mail($email,"$autosubject2","$automessage2","From: $recipientname <$recipientemail>");
}

But it's sending both emails when the user completes the referral fields. When they do not enter any referral info, it seems to work just fine (they only get the specified confirmation email). Any idea what I'm doing wrong?


Solution

  • If those variables are coming directly from $_POST, then they'll never be null, e.g. a url like

    http://example.com/script.php?field=
    

    will produce

    $_GET['field'] = '';
    

    and contain an empty string, not a null value.

    Beyond that, your logic is faulty, it's being parsed as:

    if (($referral_1 != '') or ($referral_2 != '') etc...)
    

    For your statement to work, you need to bracket the or bits, because or has a LOWER precedence than ==, so...

    if (($referral_1 or .... or $referal_5) == null) {
        ^---                              ^--- new brackets
    

    Which opens another can of worms. The or sequence will produce a boolean true or false, never a null. so, what you really want is simply:

    if ($referral_1 or ... $referal_5) {
       ... a referal was specified in at least ONE of those fields.
    }