2009-10-08 32 views
2

我正在使用PHP/MySQL,並且我想知道使未經身份驗證的用戶登錄的最佳方式,然後讓它們自動重定向到他們登錄的頁面登錄Interupt並使用PHP/MySQL返回到頁面

例如:

1)用戶試圖打開安全頁面。
2)它們被重新定向並提示登錄。
3)成功登錄後,它們被帶回他們嘗試訪問的URL。

目前,在我的「安全」頁面,我有以下的PHP代碼設置:(甚至不知道這是正確的方式做「安全」的話):

<?php 
session_start(); 

if ($_SESSION['first'] == "" && $_SESSION['usrID'] == "") { 

    print" <script> 
    window.location=\"../login/index.php\" 
    </script> "; 

    } 

    ?> 

任何的建議如何提供此功能(並可能使我的'安全'代碼更好),我將不勝感激。

謝謝!

回答

2

你可以在會話中存儲的VAR請求URL。

$_SESSION['destination'] = $_SERVER['REQUEST_URI']; 

然後,一旦登錄,你可以做這樣的事情:

if (isset($_SESSION['destination'])) { 

    header('Location: ' . $_SESSION['destination']); 
    exit; 
} 

而且,這不是一個好主意

print" <script> 
    window.location=\"../login/index.php\" 
    </script> "; 

使用JavaScript重定向有問題。首先,禁用JavaScript不會發生任何事情。嘗試發送位置標頭

header('Location: ../login/index.php'); 
exit; // Call exit to make sure the rest of your code never executes 
1

您可以在/login/index.php文件中檢索referrer URI並將其作爲隱藏字段提供給登錄表單。用戶登錄後,只需將他重定向到他以前嘗試訪問的頁面。

類似的東西:

/login/index.php:

<?php 

// if user submitted login form 
if(isset($_POST['login'])) { 

// do your login actions here 
// and after... 
header("Location: " . $_POST['returnto']); 

} 


// 

$user_came_from = htmlspecialchars($_SERVER['HTTP_REFERER']); 

?> 
<form name="my_login_form" action="" method="post"> 
user: <input type="text" name="user" value="" /> 
pass: <input type="password" name="pass" value="" /> 
<input type="hidden" name="returnto" value="<?php echo $user_came_from ?>" /> 
<input type="submit" name="login" value="login" /> 
</form> 
相關問題