使用PHP登录后重定向到上一页 [英] Redirect to previous page after logging in using PHP

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

问题描述

假设我要导航到联系页面.但是为了到达那里,该站点要求我登录.登录后,我应该被重定向到联系页面,但是我在其他地方.我应该怎么做才能登录后重定向到我想要的页面?

Let's say I want to navigate to the contact page. But in order to get there, the site requires me to login. After logging in, I'm supposed to be redirected to the contact page, but I'm somewhere else. What should I do such that I should be redirected to the page I want after logging in?

我有一种强烈的感觉,那就是与会话有关,尽管如此.这种方法应该是什么?

I have a strong feeling that this has something to do with sessions but nonetheless. What should the approach be?

推荐答案

您有三种通用方法:

  1. 在会话中存储上一页;
  2. 将页面存储为GET变量;或
  3. 进行内部重定向到登录页面.

(1)类似于:

<?php
session_start();
if (!$_SESSION['userid']) {
  $_SESSION['page'] = '/contact';
  header('Location: /login');
  exit;
}
...
?>

成功登录后,检索$_SESSION['page']并重定向.

On successful login retrieve $_SESSION['page'] and redirect.

(2)相似,除了没有会话变量.相反,您有:

(2) is similar except there is no session variable. Instead you have:

header('Location: /login?return=/contact');

通过重定向.登录页面必须在页面上将其作为隐藏表单字段包括在内,该页面向用户显示用户名和密码的请求.

to pass the redirect. The login page will have to include it as a hidden form field on the page that presents the user with a request for the username and password.

(3)与之类似,但不会重定向到单独的页面.相反,每个页面都可能是登录页面.如果用户未登录,则显示登录表单.该URL仍为"/contact".每个页面都会检测并处理登录尝试.

(3) is similar but doesn't redirect to a separate page. Instead each page can potentially be a login page. If the user isn't logged in a login form is presented instead. The URL will still be "/contact". Each page will detect and handle log in attempts.

此方法的优点是减少了外部重定向,并且更易于处理提交的表单.我的意思是,假设有人在您的一个页面上填写了一个表格,然后单击提交".系统看到他们的登录名已过期.如果您将用户重定向到新页面,然后重定向回新页面,则他们可能需要重新输入所有表单字段.如果您隐式处理登录,则可以将所有表单字段都包含为隐藏输入,并且一旦登录就可以无缝地将其视为原始页面的提交.

The advantage of this method is one less external redirect and it's easier to handle submitted forms. By this I mean that imagine someone fills out a form on one of your pages and then clicks submit. The system sees their login has expired. If you redirect the user to a new page and then redirect back they will probably need to re-enter all the form fields. If you handle the login implicitly you can include all the form fields as hidden inputs and once logged in seamlessly treat it as a submission of the original page.

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

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