php - 多维关联数组,用于登录的 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>';
}
}
解决方案
搜索$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'];
推荐阅读
- reporting-services - 尝试打印任何报告时出现错误“报告数据集执行期间发生错误”
- html - 围绕列的样式表
- java - Docker compose mysql 容器在依赖它的应用程序之后运行
- tinymce - WYSIWYG 编辑器在 mac Prestashop1.6 上消失了
- java - 安装后如何永远运行应用程序?
- ios - Firebase 应用内消息按钮操作不起作用
- oracle - 如何在行之间找到oracle中常见的最长子字符串?
- amazon-web-services - JHipster Gateway 没有将请求路由到微服务
- ios - Booking.com 如何以编程方式关闭他们的应用程序?
- javascript - HTML5 视频 - 如何无缝播放多个视频然后循环播放序列?