首页 > 解决方案 > 多维关联数组,用于登录的 session() 和 isset(),我做错了什么?

问题描述

我正在尝试创建一个简单的登录页面,

如果我采用以下数组变体,它可以工作:
$users = [['hello@domain.de' => 'Asd23'], ['hello2@domain.de' => 'hell5123']];
if (isset($logins[$userKey][$email]) && $logins[$userKey][$email] == $password)

但是使用以下多维关联数组变体我做不到。
我在做什么还是我弄错了?

// Multidimensional Associative Array
$users = [
  ////////////
  [
    'email' => 'sandra@domain.com',
    'password' => 'San1',
    'name' => 'Sandra',
    'lastname' => 'Meier',
    'status' => 'Admin',
    'content' => ''
  ],
  [
    'email' => 'franz@domain.com',
    'password' => 'Fra1',
    'name' => 'Franz',
    'lastname' => 'Eder',
    'status' => 'Standard',
    'content' => 'leer'
  ],
]

// check and assign submitted email and password to new variable
$email = isset($_POST['email']) ? $_POST['email'] : '';
$password = isset($_POST['password']) ? $_POST['password'] : '';

if(isset($_POST['Submit'])) {

  // find the key from the given email
  // Multidimensional Array Searching (Find key by specific value)
  $userKey = array_search($email, array_column($users, 'email'));

  // check if the given email address and password exist and match
  if (isset($users[$userKey][$email]) && $users[$userKey][$password] == $password) {
    // success: email address and password exist and the email address matches the password

    // set session variables and redirect to protected page
    $_SESSION['UserData']['email'] = $users[$userKey][$email];
    header("location:{$protocol_domain}{$actualURl}");
    exit;
  } else {
    // unsuccessful attempt: email address and password do not exist or the emails do not match

    // Set error message
    $msg = '<span style="color:red">Invalid Login Details</span>';
  }

}

标签: phparrayssession

解决方案


搜索$userKey = array_search($email, array_column($users, 'email'));将为您提供索引,例如 - 0

接下来检查是否$users[0][$email]已设置。但它没有设置,因为你没有 key $email,你有 key 'email'(一个纯字符串),对于$password/相同'password',所以检查应该是:

// you check that 
// - 'email' key is set and 
// - value in 'password' key is same as value from $_POST
if (isset($users[$userKey]['email']) && $users[$userKey]['password'] == $password) {

还将您的会话集更新为:

$_SESSION['UserData']['email'] = $users[$userKey]['email'];

推荐阅读