检查两个变量是否匹配

时间:2019-04-08 22:31:00

标签: php variables

如果两个变量基于登录的用户ID和页面ID匹配,我正在尝试回显一条消息。我已经尝试了几个小时,似乎无法获得最终结果。

无论哪种方式,我都尝试过使用==,但是无论如何我都保持“ OK”。

有效的方法: 在下面的代码中,$ userNowId给我当前会话的用户ID。 $ profileID给我特定页面ID的ID。这项工作。

这两个值都在页面上正确地回显。例如,如果我以用户ID 1身份登录,然后键入url profile.php?user = 65进入其页面,则我的数据库ID(1)和URL ID(65)均会按需显示。

问题: 现在,我想做一个if语句,说如果这两个值不匹配,则回显消息“不是您的个人资料”。不确定是否有帮助,但是我已经用OOP PHP编写了。

这就是我到目前为止所拥有的。

<?php
    require_once 'core/init.php';

    $userNow = new user();
    $userNow->LoggedInUser();

    if (!$username = input::get('user')) {
        redirect::to('index.php');
    } else {
        $user = new user($username);
        if (!$user->exists()) {
            redirect::to(404);
        } else {
            $data = $user->data();
            $userNowId = ($_SESSION && $data->id);
            $profileID = ($data->id);

            if ($userNowId == $profileID) {
                echo "Your profile";
            } else {
                echo "Not your profile!";
            }

1 个答案:

答案 0 :(得分:0)

问题在于您如何设置$userNowId

$userNowId = ($_SESSION && $data->id);

这是布尔操作,会将值设置为布尔值true或false,而不是ID。我怀疑您真正想要的是这样的东西:

$userNowId = array_key_exists('id', $_SESSION) ? (int)$_SESSION['id'] : null;
$profileID = (int)$data->id;

if ($userNowId === $profileID) {
  echo "Your profile";
} else {
  echo "Not your profile!";
}

请注意,我已经使用严格的类型比较(===)来防止将null转换为0,这会带来安全风险。我也将id强制转换为整数,以便当PHP将数据库int转换为字符串时,严格类型检查将起作用。

相关问题