2012-08-24 99 views
2

假設我想作一個超級簡單的頁面,在PHP訪問限制爲單個用戶。提供的授權用戶知道的目錄和網頁的網址,可能他只是手動通過在地址欄的get方法的用戶名和密碼(他會知道),並自動檢查其對腳本,其中用戶名和密碼的值將被硬編碼在?該腳本有一個if statement,如果不是這樣,將不會顯示內容。會有什麼缺陷?簡單的單用戶登錄頁面

的網址

http://example.com/admin.php?user=admin&password=1324 

admin.php的

<?php if($_GET['user'] == 'admin' && $_GET['password'] == '1324')){ 
// display content here 
}else{ 
echo "You're not authorized to visit this page"; 
} ?> 

方案2:在post方法

到上述場景類似,在這一個授權用戶可以鍵入用戶名,表格中的密碼,將在實際的admin.php文件中處理。類似的if statement將使用與$_POST[]超全局這次檢查輸入。

<?php if($_POST['user'] == 'admin' && $_POST['password'] == '1324'){ 
    // display content here 
}else{ 
    echo "You're not authorized to visit this page"; 
} ?> 

回答

4

驗證兩者都有自己的缺陷。

如果您使用方法1,您最終將傳遞給標題的變量保存在頁面歷史記錄中,這意味着任何有權訪問PC的人都可以搜索並找到它們,從而在過程中給予自己訪問權限。搜索引擎也可以拿起並保存鏈接,讓它向世界開放。

如果您使用方法2,您需要重新發送POST數據每一次你訪問一個安全頁面,這意味着你最終按鈕和形式的混亂,其中的鏈接可能已經足夠了。但它確實消除了第一種方法的問題。

一個更好的方法,以這兩個將是$ _SESSION變量的使用。這基本上允許數據被存儲在服務器側,同時給其可以被用來控制對數據的訪問一個「密鑰」的用戶 - 該密鑰被存儲在cookie中,默認情況下。

一個例子用法是:

//Say the user is "admin", and the password is "1234" 
//This data could be used to 'log in' via post. 
//First of all we start the session, and check to see if the user is logged in 
//If the user has the session active, they'll have a cookie on their PC which links to it 
session_start(); 
if ($_SESSION['login']==true || ($_POST['user']=="admin" && $_POST['pass']=="1234")) { 
    //If they already have a session, give them access. 
    //If not, check for posted UN & PW and if correct, give access. 
    $_SESSION['login']=true; //Set login to true in case they got in via UN & PW 
    //Do stuff for when logged in 
} 
else { //Not already logged in, not sent a password 

    //Give the user a login form redirecting to this page. 

} 

的這個好處是:

  • 沒有存儲在用戶端的密碼
  • 當瀏覽器關閉時過期
  • 會話密鑰
  • 密碼只能通過互聯網傳遞一次
+0

關於第二種方法:我只打算讓授權用戶訪問一個頁面。 '$ _SESSION []'在這裏不起作用,因爲每次登錄只發送一次數據(所以如果用戶離開受限制的頁面,他將不得不再次通過表單)。該情景最好被簡化。但是,我甚至不會想到實施這樣的系統。這個問題僅僅出於好奇而出現。 – menislici

1

是它可以與GETPOST必須從一種形式通過。這是不安全的,因爲很多原因。

但是,是的,您的需求可以用GET通過。只需一個URL,他就可以跳進禁區。

BTW,當您檢查用戶名和密碼:

if($_GET['user'] == 'admin' && $_GET['password'] == '1324' && $_GET['password'] != '' && $_GET['username'] != '') 

可以排除最後一部分,因爲你已經對數據

if($_GET['user'] == 'admin' && $_GET['password'] == '1324') 
+0

叫你能提一些hazzards的? – menislici

+1

搜索引擎可能會緩存該鏈接。它可以被蠻容易的。它是可視的。 –

+0

怎麼樣'POST',這樣的風險呢? – menislici

0

像這樣

if (!isset($_SERVER['PHP_AUTH_USER'])) { 
    header('WWW-Authenticate: Basic realm="My Realm"'); 
    header('HTTP/1.0 401 Unauthorized'); 
    echo 'Text to send if user hits Cancel button'; 
    exit; 
} else { 
    $expectdUsername = 'username'; 
    $expectedPassword = 'secret'; 

    if($_SERVER['PHP_AUTH_USER'] != $expectdUsername || 
     $_SERVER['PHP_AUTH_PW'] != $expectedPassword) { 
     echo 'Invalid username/password'; 
     exit; 
    } 

    //Add a cookie, set a flag on session or something 
    //display the page 
} 

它可以通過

http://username:[email protected]