基于简单角色的访问 php
Simple Role Based Access php
登录时,我执行 session_start() 然后设置以下会话变量:
$_SESSION['id'] = $row['id'];
$_SESSION['role'] = $row['role'];
$_SESSION['customer_id'] = $row['customer_id'];
稍后,在另一个 php 中,我检查了这些 $_SESSION 变量的值以确定将使用哪个 SELECT 语句来访问数据库,如下所示:
$sess_cid = $_SESSION['customer_id'];
if ($_SESSION['role'] = 1) {
$sql = 'SELECT * FROM my_table';
} elseif ($_SESSION['role'] = 2) {
$sql = 'SELECT * FROM my_table WHERE id = "$sess_cid"';
} else {
echo "not authorized to access app";
}
我没有正确格式化 if() 吗?一切都应该在数据库中设置为 INT 值。
试试这个:
$sess_cid = $_SESSION['customer_id'];
if ($_SESSION['role'] == 1) {
$sql = 'SELECT * FROM my_table';
} else if ($_SESSION['role'] == 2) {
$sql = 'SELECT * FROM my_table WHERE id = "$sess_cid"';
} else {
echo "not authorized to access app";
}
您必须使用“==”运算符比较会话值。
我什至建议您在多个 if else 上使用 Switch 语句。
$sess_cid = $_SESSION['customer_id'];
switch($_SESSION['role']) {
case 1:
$sql = 'SELECT * FROM my_table';
// do whatever you want to do here..
break;
case 2:
$sql = 'SELECT * FROM my_table WHERE id = "$sess_cid"';
// do whatever you want to do here..
break;
default:
echo "not authorized to access app";
break;
}
登录时,我执行 session_start() 然后设置以下会话变量:
$_SESSION['id'] = $row['id'];
$_SESSION['role'] = $row['role'];
$_SESSION['customer_id'] = $row['customer_id'];
稍后,在另一个 php 中,我检查了这些 $_SESSION 变量的值以确定将使用哪个 SELECT 语句来访问数据库,如下所示:
$sess_cid = $_SESSION['customer_id'];
if ($_SESSION['role'] = 1) {
$sql = 'SELECT * FROM my_table';
} elseif ($_SESSION['role'] = 2) {
$sql = 'SELECT * FROM my_table WHERE id = "$sess_cid"';
} else {
echo "not authorized to access app";
}
我没有正确格式化 if() 吗?一切都应该在数据库中设置为 INT 值。
试试这个:
$sess_cid = $_SESSION['customer_id'];
if ($_SESSION['role'] == 1) {
$sql = 'SELECT * FROM my_table';
} else if ($_SESSION['role'] == 2) {
$sql = 'SELECT * FROM my_table WHERE id = "$sess_cid"';
} else {
echo "not authorized to access app";
}
您必须使用“==”运算符比较会话值。
我什至建议您在多个 if else 上使用 Switch 语句。
$sess_cid = $_SESSION['customer_id'];
switch($_SESSION['role']) {
case 1:
$sql = 'SELECT * FROM my_table';
// do whatever you want to do here..
break;
case 2:
$sql = 'SELECT * FROM my_table WHERE id = "$sess_cid"';
// do whatever you want to do here..
break;
default:
echo "not authorized to access app";
break;
}