2016-03-30 27 views
1

セッションを使用してウェブサイトでログインシステムを使用しました。セッションを使用してページへのアクセスを制限する

これは

<?php 
session_start(); 

ob_start(); 

include 'includes/db.php'; 

$idadm=$_POST['idadm']; 
$passadm=$_POST['passadm']; 

$idadm = stripslashes($idadm); 
$passadm = stripslashes($passadm); 
$idadm = mysql_real_escape_string($idadm); 
$passadm = mysql_real_escape_string($passadm); 

$sql="SELECT * FROM admin WHERE aid='$idadm' and password='$passadm'"; 
$result = $conn->query($sql); 

$count = $result->num_rows; 

if($count == 1) { 
    $_SESSION['idadm'] = $idadm; 
    $_SESSION['passadm'] = $passadm; 

if ($_SESSION['idadm'] == 'admin') { 
    header("location:admin/index.php"); 
} else { 
    header("location:subadmin/index.php"); 
} 
} else { 
    header("location:index.php"); 
} 

ob_end_flush(); 
?> 

をdb.phpは、データベースの資格情報を持っている、それがどのように見えるかです。

この

<?php 
    session_start(); 
    if (!isset($_SESSION['idadm'])) { 
     header('location:/index.php'); 
     die; 
} 
?> 

ログインスクリプトは、両方の管理者とsubadminページにアクセスできるユーザーでログインして、一つの問題を除いて正常に動作し、保護されたページの一番上にあるコードです。

管理者ユーザーは1人で、そのユーザーのデータベース内のIDは「admin」です。管理者は 'admin/index.php'にしかアクセスできず、他のユーザーは 'subadmin/index.php'にアクセスできるはずです。

これを行うためにスクリプトを変更するにはどうすればよいですか?

答えて

0

だから、最初に、$_SESSION["idadm"]$_SESSION['passadm'] ...

だから、まず自分の管理ページでこのなります:

<?php 
    session_start(); 
    if (!isset($_SESSION['idadm'])) { 
     header('location:/index.php'); 
     die; 
    } else { 
     $username = $_SESSION["idadm"]; 
     $password = $_SESSION['passadm']; // Also storing passwords in session vars is not a good idea. :/ 

そして、DB接続を開く:

$pdo = new PDO($dsn, $DBUsername, $DBPass): 
// or 
$mysqli = mysqli_connect($host, $DBUsername, $DBPass, "admin") 

次に、現在のユーザー名とパスワードがデータベースに存在するかどうかを確認します。

私はPDOでそれをやっている:

$sth = $pdo->prepare("SELECT COUNT(*) AS number_of_users FROM table_name WHERE aid = :username AND password = :password"); 
$sth->bindParam(":username", $username, PDO::PARAM_STR); 
$sth->bindParam(":password", hash("YOUR_HASHING_ALGO", $password), PDO::PARAM_STR); // If you have not hashed the password you can remove the hash method, but not hashing a password is a horrible idea 
$result = $sth->fetch(PDO::FETCH_ASSOC); 
if((int) $result["number_of_users"] >= 1) { 
    // yay he is an admin, do somethin' 
} else { 
    // nope, he is not allowed to enter, what to do with him? 
} 

そして最後近くで

と他のブロック:では

} 

接続文字列のあなた自身の特定の資格情報とDBを使用する必要があります。

希望すると助かります!

関連する問題