我想開發一個登錄系統,客戶和管理員都可以登錄。客戶將被髮回索引,管理員將被髮送到控制面板。我在我的數據庫中有一個用戶表。這裏有一個定義用戶的級別;客戶級別= 1,管理員級別= 0.PHP登錄客戶和管理
我對PHP很陌生,一直在尋找答案。我發現了我需要的兩個版本。我不是100%肯定他們是正確的,哪個是最好用的。
實施例1:
//indicate that sessions are to be used or started
session_start();
// Define $myusername and $mypassword from the form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
// Query
$result= $dbh->query("SELECT * FROM users WHERE username='$myusername' AND password='$mypassword';");
// Mysql_num_row is counting table row
$count = $result->rowCount();
// Determine if user is "user" or "admin"
$userlevel = mysqli_query($con,"SELECT level FROM users WHERE username='$myusername';");
$level = mysql_fetch_row($userlevel);
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1) {
// Start session, register $myusername, $mypassword and redirect to login_success.php
session_start();
$_SESSION['myusername'] = $myusername;
$_SESSION['mypassword'] = $mypassword;
$_SESSION['level'] = $level;
// Redirect to appropriate page depending on user rights. Indicator 0 for user, 1 for admin.
if($_SESSION['level'] == 0)
{
//Admin Login
header("location:../php/admin.php");
}
if ($_SESSION['level']) == 1)
{
//Customer login
header("location:../login_success.php");
}
//flush the output buffer
ob_end_flush();
?>
實施例2:
// Define $myusername and $mypassword from the form
$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];
$sql="SELECT * FROM users WHERE username='$myusername' and password='$mypassword' and level== '0'";
if($count==1){
$_SESSION["username"] = $username;
$_SESSION["password"] = $password;
$info = mysql_fetch_array($result);
if ($info['level'] == 0) {
header("location:../php/admin.php");
}
else
header("location:../index.html");
}
}
else {
echo "Incorrect password";
}
?>
任何幫助將不勝感激。
兩者都有嚴重的錯誤和漏洞(如,但可能不限於,SQL注入和純文本密碼也許調查輕量級有據可查的框架,將建立在此方法 – Steve
我已經防止SQL注入(只是沒有包括在這裏的代碼中)我只想登錄系統工作。僅適用於測試網站。 – LaurenA