根据复选框选择执行PHP操作

myzjeezk  于 2023-04-19  发布在  PHP
关注(0)|答案(1)|浏览(120)

我有一个工作的PHP邮件脚本,现在我试图修改它的行动的基础上两个复选框。
下面是HTML中两个复选框的HTML

<ul class="checkboxColumns">
    <li><label><input type="checkbox" name="1004124a662d8161e3e2cb602f73e81d[newsletter_digest][newsletter_receive]" value="newletter_receive"> Newsletter</label></li>
    <li><label><input type="checkbox" name="1004124a662d8161e3e2cb602f73e81d[newsletter_digest][forumdigest_receive]" value="forumdigest_receive"> Forum Digest</label></li>
</ul>

该随机字符串例如‘1004124 a662 d8161 e3 e2 cb 602 f73 e81 d’由核心应用在每个会话上生成作为保护机制。
一些关于价值观的解释:

newsletter_digest=group of two checkboxes
newsletter_receive = value of first checkbox
forumdigest_receive = value of second checkbox

我尝试的PHP代码是这样的

if ($user['user_state'] == 'email_confirm')
    {
        $this->_getUserConfirmationModel()->sendEmailConfirmation($user);
    }
    // Check if newsletter and forum digest checkboxes are checked
    $newsletterChecked = !empty($_POST['newsletter_receive']);
    $forumDigestChecked = !empty($_POST['forumdigest_receive']);
    
    
    if (!$newsletterChecked && !$forumDigestChecked) {
        // Case 1: When value="newsletter_receive" and value="forumdigest_receive" are both empty, not checked --> do Action 1
    } elseif ($newsletterChecked && $forumDigestChecked) {
        // Case 2: When value="newsletter_receive" value="forumdigest_receive" are both checked --> do Action 2
    } elseif ($newsletterChecked && !$forumDigestChecked) {
        // Case 3: When value="newsletter_receive"  is checked but value="forumdigest_receive" is left empty --> do Action 3
    } elseif (!$newsletterChecked && $forumDigestChecked) {
        // Case 4: When value="newsletter_receive" is left empty but value="forumdigest_receive" is checked --> do Action 4
    }

    return $this->_completeRegistration($user);
}

我尝试了这个简单的if/elseif逻辑,但由于一些奇怪的原因,它不起作用,因为在所有情况下,它从来没有拿起复选框上的复选框,但它总是“认为”它是情况1时,复选框是空的。我甚至把情况1代码放在底部,它仍然选择这个动作。
即使是这种初步检查似乎也不起作用

$newsletterChecked = !empty($input['newsletter_receive']) ? true : false;
$forumDigestChecked = !empty($input['forumdigest_receive']) ? true : false;

我认为问题是php没有选择前端的html由于随机字符串?
任何帮助都非常感谢

dbf7pr2w

dbf7pr2w1#

一个快速而肮脏的解决方案是循环$_POST,看看值是否是一个数组,键newsletter_digest是否存在。还有其他解决方案,但这很简单,也很中肯。

$newsletters = [];
foreach($_POST as $k => $v){
    if(is_array($v) && isset($v["newsletter_digest"])){
        $newsletters = $v["newsletter_digest"];
    }
}

如果两者都被选中,结果将是这样的数组:

Array
(
    [newsletter_receive] => newletter_receive
    [forumdigest_receive] => forumdigest_receive
)

如果有一个被选中的话,就像这样

Array
(
    [newsletter_receive] => newletter_receive
)

然后你可以做一些像

$newsletterChecked = isset($newsletters['newsletter_receive']);
$forumDigestChecked = isset($newsletters['forumdigest_receive']);

相关问题