I have a text field in a contact form, users have to reply to a simple question (I know is not the best way to approach spam, we already have other things captcha, honeypots and more).
The question is that I just want to give the user the option of 2 answers.
if ($_POST['answer'] == "banana") {
// we're OK, do something
} else {
alert("YOU FAILED!!!");
}
I want the text field to pass with more than 1 word, let's say "foo" and "baz"
How do I solve this problem?
答案 0 :(得分:1)
@tim(间接)建议使用逻辑运算符。使用的解决方案如下所示:
if ($_POST['answer'] == 'banana' || $_POST['answer'] == 'platano') {
如果需要检查的条件彼此不相关(例如,如果需要检查来自两个不同表单字段的值),这就是方法。但是,根据您的情况,建议您检查提供的值是否在可接受的值列表中:
if (in_array($_POST['answer'], ['banana', 'platano'])) {
在二值情况下,这是稍微短一点的代码(并且,我想,它更具可读性,因此更易于维护),但是如果发现需要添加第三和第四个选项,则代码会变得越来越好。