PHP重定向回上一页 [英] PHP redirect back to previous page

查看:53
本文介绍了PHP重定向回上一页的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 login.php 页面所做的是,如果用户已经登录,他将被重定向到 first.php 页面.

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");
} 

在所有其他页面中,如果用户还没有登录,他将被重定向到 login.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");
} 

问题来了:有没有办法将用户重定向回他来自的地方?假设您在未登录时尝试访问 second.php,您现在将被重定向到 login.php 页面;登录后,是否可以重定向回 second.php 而不是 first.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?

我曾尝试使用 $_SERVER['HTTP_REFERER'],但该变量不包含任何内容;它只包含一些内容,如果您在这里是因为您点击了一个链接.

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.

推荐答案

  1. 在他们尝试登录的页面上设置一个包含该页面 URL 的会话变量.
  2. 然后将它们重定向到登录页面.
  3. 成功登录后,从他们的会话中获取之前的 URL 并将其重定向到那里.

让执行重定向的页面设置一个会话变量,即该页面的 URL:

Have the page that does the redirecting set a session variable that is the URL of that page:

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

然后在成功登录后将他们重定向到该 URL:

Then after a successful login redirect them to that 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;

上述内容可以改进,但这应该会给你思路.

The above can be improved upon but this should give you the idea.

这篇关于PHP重定向回上一页的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆