简体   繁体   English

成功登录后如何重定向到引用页面/ URL?

[英]How do I redirect to referring page/url after successful login?

I'm aware that this topic has been covered before here on Stack, and I have looked at some answers, but I'm still a bit stuck, being fairly new to PHP. 我知道这个话题已经在Stack上讨论过了,我已经看了一些答案,但是对于PHP还是一个新手,我还是有点困惑。 Every page on my website requires a login, and so users are redirected to a login page on page load. 我网站上的每个页面都需要登录,因此在页面加载时将用户重定向到登录页面。 At the top of each page then I have: 在每个页面的顶部,我有:

<?
require("log.php");
include_once("config.php"); 
include_once("functions.php"); 
?>

This redirects the user to log.php (with new code added): 这会将用户重定向到log.php(添加了新代码):

<?
session_name("MyLogin");
session_start();

    if(isset($_SESSION['url'])) 
       $url = $_SESSION['url']; // holds url for last page visited.
    else 
       $url = "index.php"; // default page for

if($_GET['action'] == "login") {
$conn = mysql_connect("localhost","",""); // your MySQL connection data
$db = mysql_select_db(""); //put your database name in here 
$name = $_POST['user'];
$q_user = mysql_query("SELECT * FROM users WHERE login='$name'");

if (!$q_user) {
    die(mysql_error());
}

if(mysql_num_rows($q_user) == 1) {

$query = mysql_query("SELECT * FROM users WHERE login='$name'");
$data = mysql_fetch_array($query);
if($_POST['pwd'] == $data['password']) { 
$_SESSION["name"] = $name;
header("Location: http://monthlymixup.com/$url"); // success page. put the URL you want 
exit;
} else {
header("Location: login.php?login=failed&cause=".urlencode('Wrong Password'));
exit;
}
} else {
header("Location: login.php?login=failed&cause=".urlencode('Invalid User'));
exit;
}
}

// if the session is not registered
if(session_is_registered("name") == false) {
header("Location: login.php");
}

?>

The login form is contained in login.php. 登录表单包含在login.php中。 The code for login.pho relevant to the PHP/log.php is: 与PHP / log.php相关的login.pho的代码为:

<?
session_start();

if($_GET['login'] == "failed") {
print $_GET['cause'];
}
?>

and

<form name="login_form" id="form" method="post" action="log.php?action=login">

The answer that I came across stated that I should add: 我遇到的答案指出,我应该添加:

session_start(); // starts the session
$_SESSION['url'] = $_SERVER['REQUEST_URI'];

to the top of each page, which I did, at the top of the page (above "require("log.php");"), and then add: 到我做过的每个页面的顶部(在“ require(“ log.php”);“上方),然后添加:

if(isset($_SESSION['url'])) 
   $url = $_SESSION['url']; // holds url for last page visited.
else 
   $url = "index.php"; // default page for

to my login page, and use the following URL for redirect on successful login: 到我的登录页面,并使用以下URL在成功登录后进行重定向:

header("Location: http://example.com/$url"); // perform correct redirect.

I am not 100% where the code which stores the referring URL should go, at the top of log.php or login.php. 在log.php或login.php的顶部,我不是100%应该存储引用URL的代码。

I have tried adding it to both, but the login page is just looping once I have entered the username and password. 我尝试将其添加到两者中,但是一旦输入用户名和密码,登录页面就会循环播放。

I wonder if someone could help me get this working? 我想知道是否有人可以帮助我完成这项工作?

Thanks, 谢谢,

Nick 缺口

It appears that I don't have the privilege to comment on your post, so I'll do the best that I can to answer. 看来我没有特权对您的帖子发表评论,因此,我将尽我所能回答。 I apologize for all of the scenarios, I'm just doing the best I can to answer on a whim. 对于所有情况我都表示歉意,我只是尽力想尽办法回答。

SCENARIO 1: 场景1:

If you've truly not selected a database in your code, as demonstrated here, could that potentially be your issue? 如果您确实没有在代码中选择数据库(如此处所示),可能是您遇到的问题吗? Please do note, that the code below, is the code you've posted. 请注意,下面的代码是您发布的代码。

$db = mysql_select_db(""); //put your database name in here 

SCENARIO 2: 场景2:

The code below is not something I've ever used in anything I've built, might I suggest that you try replacing that line of code with the line below it? 下面的代码不是我用过的任何东西,我是否建议您尝试用下面的代码替换那行代码?

if(session_is_registered("name") == false) { // Current
if(isset($_SESSION['name']) == false) { // Potential Replacement

SCENARIO 3: 场景3:

If you're logic for the following, exists on the login.php file as well... That could potentially be your problem. 如果您出于以下逻辑考虑,则login.php文件中也存在该文件...这可能是您的问题。 Upon visiting your site, I noticed your form appears on login.php, yet your logic is posting to log.php. 访问您的网站后,我注意到您的表单出现在login.php上,但是您的逻辑正在发布到log.php。 I'm hoping this bit of code can help rule out that "jump", as login.php might be saving itself and overwriting the $_SESSION variable you've established 我希望这段代码可以帮助排除“跳转”,因为login.php可能会保存自身并覆盖已建立的$ _SESSION变量

session_start(); // starts the session
$_SESSION['url'] = $_SERVER['REQUEST_URI'];

If it's too complex to take it out of the login.php file, if you even have it there, I've put together some code that you can use to create "internal" breadcrumbs, so you can go 2 pages back in your history. 如果太复杂以至于无法从login.php文件中删除它,甚至在其中也没有,我已经整理了一些可用于创建“内部”面包屑的代码,因此您可以将历史回溯两页。

    if(!isset($_SESSION['internal_breadcrumbs']))
        $_SESSION['internal_breadcrumbs'] = array();

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

    $max_breadcrumbs = 5;

    while(count($_SESSION['internal_breadcrumbs']) > $max_breadcrumbs)
        array_shift($_SESSION['internal_breadcrumbs']);

That will create an array with a max of $max_breadcrumbs elements, with your most recent page at the end, like the following 这将创建一个数组,其中最多包含$ max_breadcrumbs个元素,最后一个页面位于末尾,如下所示

Array
(
    [internal_breadcrumbs] => Array
        (
            [0] => /other_page.php
            [1] => /other_page.php
            [2] => /other_page.php
            [3] => /user_page.php <-- desired page
            [4] => /login.php <-- most recent page
        )

)

So now... you can setup your url to be something more like the following... 所以现在...您可以将您的网址设置为类似于以下内容...

// I'm doing - 2 to accommodate for zero indexing, to get 1 from the current page
if(isset($_SESSION['internal_breadcrumbs'])) 
    $url = $_SESSION['internal_breadcrumbs'][count($_SESSION['internal_breadcrumbs']) - 2];
else 
   $url = "index.php"; // default page for

All the best, and I certainly hope this has helped in some way. 一切顺利,我当然希望这能有所帮助。

IN SCENARIO 4 在场景4中

From the client test the login/password which ajax XMLHttpRequest with javascript code to a dedicated script for validation (do it on mode https for secure) 从客户端测试使用javascript代码的ajax XMLHttpRequest的登录名/密码到专用脚本进行验证(在模式https上进行以确保安全)

If response is right send the login password to your script server. 如果响应正确,则将登录密码发送到脚本服务器。

Stips : Encoding password is better secure ! 提示:编码密码更安全!

Using header() function it's a bad idea. 使用header()函数是个坏主意。

Manual specification say ; 说明书说明;

Remember that header() must be called before any actual output is sent, either by normal HTML tags, blank lines in a file, or from PHP. 请记住,必须先通过常规HTML标记,文件中的空白行或从PHP发送任何实际输出,然后调用header()。 It is a very common error to read code with include, or require, functions, or another file access function, and have spaces or empty lines that are output before header() is called. 读取包含,或要求函数或另一个文件访问函数的代码,并在调用header()之前输出空格或空行,这是一个非常常见的错误。 The same problem exists when using a single PHP/HTML file. 使用单个PHP / HTML文件时,存在相同的问题。

So in your case, i suggest that to use cookies with an ID generate only for the session, at the first connection its generate, and the duration of the cookie maybe for only from 2 to 10 minutes. 因此,在您的情况下,我建议使用仅为会话生成ID的cookie,在第一次连接时生成cookie,并且cookie的持续时间可能仅持续2至10分钟。

Regenerate cookie each time the loging.PHP is called ! 每次调用loging.PHP时都要重新生成cookie!

Have a nice day 祝你今天愉快

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM