3

What I have done for the login.php page is if a user has logged in, he will be redirected to first.php page.

session_start();
if(isset($_SESSION['usr']) && isset($_SESSION['pswd'])){
    header("Location: first.php");
} 

In all other pages, if user hasn't logged in he will be redirected to login.php page.

session_start();
if(!isset($_SESSION['usr']) || !isset($_SESSION['pswd'])){
    header("Location: login.php");
} 

Here is the problem: is there a way to redirect the user back to where he was from? Say if you are trying to reach second.php while you are not logged in, you will be redirected to login.php page now; once you log in, can you be redirected back to second.php instead of first.php?

I have tried to use $_SERVER['HTTP_REFERER'], but this variable doesn't contain anything; it only contain something if you are here because you have clicked a link.

4

2 に答える 2

6
  1. ログインしようとするページで、そのページの URL を含むセッション変数を設定します。
  2. 次に、ログイン ページにリダイレクトします。
  3. ログインに成功したら、セッションから以前の URL を取得し、そこにリダイレクトします。

リダイレクトを行うページで、そのページの URL であるセッション変数を設定します。

session_start();
if (!$logged_in)
{
    $_SESSION['redirect_url'] = $_SERVER['PHP_SELF']; 
    header('Location: login.php');
    exit;
}

次に、ログインに成功した後、その URL にリダイレクトします。

session_start();

/* Login code goes here */

$redirect_url = (isset($_SESSION['redirect_url'])) ? $_SESSION['redirect_url'] : '/';
unset($_SESSION['redirect_url']);
header("Location: $redirect_url", true, 303);
exit;

上記は改善できますが、これでアイデアが得られるはずです。

于 2013-07-25T01:09:45.137 に答える
2

$_SERVER['HTTP_REFERER'] は Web ブラウザに依存し、すべてのブラウザがリファラーをサーバーに送り返すわけではありません。多くの大規模なサイトで使用されているより良いアプローチは、現在のページをログイン ページに渡すことです。

header("Location: first.php?".$currentPageUrl);

$currentPageUrl は、$_SERVER['REQUEST_URI'] または $_SERVER['PHP_SELF'] から取得できます。

ログインすると、ユーザーを $currentPageUrl に再度リダイレクトできます。

これとは別に、ユーザー名とパスワードを $_SESSION に保存するのは正しくないように思えますが、これは別の問題です。

于 2013-07-25T01:14:15.807 に答える