首页 > 解决方案 > Login.php 不重定向

问题描述

我一直在尝试锻炼为什么我不能让这个 php 代码在登录后从 index.php 重定向到 profile.php。

login.php 的工作原理是我可以手动转到 profile.php 并且它会被登录。

if ( password_verify($_POST['password'], $user['password']) ) {

    $_SESSION['email'] = $user['email'];
    $_SESSION['first_name'] = $user['first_name'];
    $_SESSION['last_name'] = $user['last_name'];
    $_SESSION['active'] = $user['active'];

    // This is how we'll know the user is logged in
    $_SESSION['logged_in'] = true;

    header("location: profile.php");
} else {
    $_SESSION['message'] = "You have entered wrong password, try again!";
    header("location: error.php");
}

我已经研究过了,并尝试了不同的方法和不同的网址,但到目前为止还没有成功。

任何帮助都会很棒!

标签: php

解决方案


header() 函数只有在执行前有 0 个输出时才会起作用。打印到浏览器的任何内容都会导致“标题已发送”,警告。您可以做的是使用元刷新标签甚至 JavaScript 重定向

<meta http-equiv="refresh" content="5; url=http://example.com/">

5 是重定向生效前的秒数。如果您希望它是即时的,请输入 0。

或者你可以在 JavaScript 中这样做:

// similar behaviour as an HTTP redirect
window.location.replace("http://stackoverflow.com");

// similar behaviour as clicking on a link
window.location.href = "http://stackoverflow.com";

为了使您的 PHP header() 函数正常工作,请确保之前没有输出任何内容。您可以打开 PHP 错误以查看是否有其他原因阻止代码执行。

如果没有更多关于究竟发生了什么或没有提供您收到的消息错误的信息,这是我能给您的最佳答案。请发布更多信息,我很乐意编辑。


推荐阅读