PHP如果值为null,则发送电子邮件

时间:2012-04-09 19:06:45

标签: php comparison-operators

我有一个处理表单的PHP脚本,但如果用户输入了一组特定字段(referral_1referral_2等)的任何信息,我想发送一封特定的确认电子邮件。)

现在我要检查用户是否在推介栏中输入了任何信息(文字输入):

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>");
}

但是当用户完成推荐字段时,它会发送两封电子邮件。当他们没有输入任何推荐信息时,它似乎工作正常(他们只获得指定的确认电子邮件)。知道我做错了吗?

4 个答案:

答案 0 :(得分:2)

PHP布尔比较不能以这种方式工作。您不能通过与第一个或最后一个参数的比较来链接它们。相反,你需要像:

// Build an array of all the values and test NULL appears in the array
if(in_array(NULL, array($referral_1, $referral_2, $referral_3, $referral_4, $referral_5)) {

// ADDED:
// To test if any value is NOT NULL, you can't use in_array(). Instead you can use
// array_filter() and check if the output array has any values
// This is complicated, and unless there are a lot of values to check, I'd probably just write
// out all each one longhand...
if (count(array_filter(array($referral_1, $referral_2, $referral_3, $referral_4, $referral_5), function($v) {return !is_null($v);})) > 0) {
   // There's a non-null
}

注意要在array_filter()中使用匿名函数,需要使用PHP 5.3。

或者通过对每个人的完整比较来写出来:

if($referral_1 === NULL or $referral_2 === NULL or $referral_3 === NULL or $referral_4 === NULL or $referral_5 === null) {

按照您的方式进行,PHP的短路评估接管,列表中的第一个非null 值返回TRUE,使整个事情为真。

答案 1 :(得分:2)

如果这些变量直接来自$ _POST,那么它们永远不会为空,例如像

这样的网址
http://example.com/script.php?field=

将产生

$_GET['field'] = '';

并包含一个空字符串,而不是空值。

除此之外,你的逻辑是错误的,它被解析为:

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

要使您的语句生效,您需要括or位,因为or的优先级低于==,所以......

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

这会打开另一种蠕虫病毒。 or序列将产生布尔值true或false,而不是null。所以,你真正想要的只是:

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

答案 2 :(得分:1)

您必须分别检查每个referrer变量以查看它们是否为null:

if(is_null($referral_1) || is_null($referral_2) || is_null($referral_3) || is_null($referral_4) || is_null($referral_5)) {

我还建议使用is_null代替== null

答案 3 :(得分:1)

我会利用isset()如果值为null则返回false,并且它可以检查多个值的事实:

if (isset($referral_1, $referral_2, $referral_3, $referral_4, $referral_5)) {
 // all values are not-null
} else {
 // at least one value is not null
}

如果要检查所有值是否为空:

if (is_null($referral_1) and is_null($referral_2) and is_null($referral_3) and is_null($referral_4) and is_null($referral_5)) {
// all values are null
}
相关问题