将两个php请求合并为一个

时间:2017-08-08 15:48:56

标签: php if-statement

感谢你的帮助。 如何向同一行添加另一个条件。我有2个请求我需要加入,我也有这个

 if (!@$_REQUEST['urEmail']) { $errorsAndAlerts .= "No email entered!<br/>\n"; }

但我还需要添加它

 if (!@$_REQUEST['g-recaptcha-response'])

我试过了

if (!@$_REQUEST['urEmail']) || (!@$_REQUEST['g-recaptcha-response']) { $errorsAndAlerts .= "No email entered!<br/>\n"; }

和这个

if (!@$_REQUEST['urEmail']) && (!@$_REQUEST['g-recaptcha-response']) { $errorsAndAlerts .= "No email entered!<br/>\n"; }

但它工作得更好了。 我很感激任何帮助。

谢谢

2 个答案:

答案 0 :(得分:0)

你的条件都需要在if括号内,如下:

if (!@$_REQUEST['urEmail'] || !@$_REQUEST['g-recaptcha-response']) { $errorsAndAlerts .= "No email entered!<br/>\n"; }

if (!@$_REQUEST['urEmail'] && !@$_REQUEST['g-recaptcha-response']) { $errorsAndAlerts .= "No email entered!<br/>\n"; }

if构造的PHP结构如下(取自PHP documentation):

if (expr)
    statement

而且,在您的情况下,expr是您的两个条件,因此您需要将它们括在括号中。

答案 1 :(得分:0)

重申我的评论,请勿使用@取消警告,修复脚本,以免发生错误。使用empty()功能确保它已填满。您可以将其与trim()结合使用以删除空格,如果已删除空格,请使用filter_var($email,FILTER_VALIDATE_EMAIL)验证其是否为有效的电子邮件模式。

示例:

# Check the email is set and trim it
$email = (isset($_REQUEST['urEmail']))? trim($_REQUEST['urEmail']) : false;
# Check the recaptcha is set and trim it
$recap = (isset($_REQUEST['g-recaptcha-response']))? trim($_REQUEST['g-recaptcha-response']) : false;
# If either are empty
if(empty($email) || empty($recap)) {
    $errorsAndAlerts .= "No email entered!<br/>\n";
}
# If both filled but invalid email
elseif(!filter_var($email,FILTER_VALIDATE_EMAIL)) {
    $errorsAndAlerts .= "Email invalid!<br/>\n";
}
//etc...

无论如何,正如 @ Don&#tpanic 所提到的那样,请确保您在ini_set('display_errors',1); error_reporting(E_ALL);上有错误报告,但我怀疑您这样做,因为您正在抑制错误/警告@

最后要注意的是,为了减轻一些重复,我可能会考虑将错误保存到数组并最终将它们包含在内:

# Save all errors using the push
# (mine are in a line, but yours would be throughout your script)
$error[] = "No email entered";
$error[] = "Invalid request";
$error[] = "Invalid email";
$error[] = "Poor penmanship";
# Implode with the glue when you want to output them
echo implode('!<br />'.PHP_EOL,$error).'!';