Php 年龄检查表

Php age check form

我在 php 上迈出了第一步,我得到了这个项目,虽然我明白正在做什么,但由于某种原因它不起作用。

$app->post('/age/', function($lang) use($app) {

        $action = $app->request()->post('action');
        $remember = $app->request->post('remember') === 'on';

        if ($action === 'Yes') {

            setcookie('AgeCheck', 'true', time()+60*60*24*30, '/'); //Expire in 1 month
            $_SESSION['age'] = 'true';

            $app->redirect(urldecode($app->request()->get('return')) ?: "/$lang");
        }
        else if ($action === 'Enter') {

            $limit = (60 * 60 * 24 * 365) * 18;

            $dob = $app->request->post('dob');

            if ($lang === 'us') {
                $dob = \DateTime::createFormFormat('mdy', $dob);
                $limit = (60 * 60 * 24 * 365) * 21;
            }
            else
            {
                $dob = \DateTime::createFromFormat('dmy', $dob);
            }

            if ((time() - $dob->getTimestamp()) >= $limit)
            {
                setcookie('AgeCheck', 1, (60*60*24*365)/12); //Expire in 1 month
                $_SESSION['age'] = 1;

                $app->redirect(urldecode($app->request()->get('return')) ?: "/$lang");
            }
        }

        $app->redirect("/$lang/underage");

理论上,如果用户超过年龄限制,这应该将用户重定向到正确的页面,但它总是将他重定向到未成年页面。

问题肯定是在这里:if ((time() - $dob->getTimestamp()) >= $limit)

我做错了什么?

始终检查代码的每一行。 您的关键条件是:

if ((time() - $dob->getTimestamp()) >= $limit)
{
    setcookie('DrambuieAgeCheck', 1, (60*60*24*365)/12); //Expire in 1 month
    $_SESSION['age'] = 1;
    $app->redirect(urldecode($app->request()->get('return')) ?: "/$lang");
}

所以在那之前,只有 echo/var_dump $dob->getTimestamp() 和 $limit。一切都会对你很清楚。 如果 $dob 有问题,请检查 $_POST['dob'] 返回的内容。

示例:

var_dump($dob->getTimestamp());
var_dump($app->request->post('dob'));
var_dump($dob->getTimestamp());
var_dump(time());
echo 'condition result:';
var_dump(((time() - $dob->getTimestamp()));
if ((time() - $dob->getTimestamp()) >= $limit)

您将在条件中看到最重要的变量,并自行调整它

解决了这个问题。一切都正确,但它甚至没有输入 if,因为 $action 不是输入,而是提交。我仍然认为@Daimos 的回答是正确的。

The more interesting part here is that ((time() - $dob->getTimestamp()) >= $limit) is actually true(in this context). So maybe the $action is not Enter? – Andrew

这是解决它的关键,在我尝试了所有方法并检查它是否正确之后。