gpt4 book ai didi

php - !is_null() 没有按预期工作

转载 作者:行者123 更新时间:2023-12-05 08:16:39 24 4
gpt4 key购买 nike

dispatch_address_postcode

不是强制性的,即使它是空白的,它仍然会运行:

if (!is_null($_POST['personal_info_first_name']) && 
!is_null($_POST['personal_info_surname']) &&
!is_null($_POST['personal_info_email']) &&
!is_null($_POST['personal_info_telephone']) &&
!is_null($_POST['dispatch_address_country']) &&
!is_null($_POST['dispatch_address_first_name']) &&
!is_null($_POST['dispatch_address_surname']) &&
!is_null($_POST['dispatch_address_address']) &&
!is_null($_POST['dispatch_address_town']) &&
!is_null($_POST['dispatch_address_postcode']) &&
!is_null($_POST['dispatch_address_county']) &&
( ($_POST['payment_method'] == "Pay by credit card.") ||
(
($_POST['payment_method'] == "Pay by new credit card.") &&
!is_null($_POST['card_number']) &&
!is_null($_POST['expiration_date']) &&
!is_null($_POST['security_code'])
)
)
)

什么给了?

最佳答案

"dispatch_address_postcode isn't mandatory and it will still run even if it's blank…"

再看看那句话。如果该字段不是必填字段,则如果该字段为空,则代码运行完全没问题。如果某个字段不是必填字段,请不要将其测试为必填字段。

但真正的问题是,is_null 仅测试变量是否为 null。发布的值永远不会是 null,如果它们是空的,它们将是 ''(一个空字符串)。您所有的 !is_null 测试都将始终true,如果变量未设置(您未设置),您将收到警告想要发生)。更合适的测试是 !empty .

更合适的测试包括测试该值是否有效(电子邮件是否看起来像电子邮件地址,电话中是否至少有 x 位数字?)。您还应该遍历字段以使您的代码更具可读性,无休止的嵌套和链接的 if 条件看起来并不令人愉快。

$mandatoryFields = array('foo' => 'email', 'bar' => 'telephone');

foreach ($mandatoryFields as $field => $rule) {
if (empty($_POST[$field]) || !validateByRule($_POST[$field], $rule)) {
raiseHell();
}
}

关于php - !is_null() 没有按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3285618/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com