php - 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");
}
我已经研究过了,并尝试了不同的方法和不同的网址,但到目前为止还没有成功。
任何帮助都会很棒!
解决方案
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 错误以查看是否有其他原因阻止代码执行。
如果没有更多关于究竟发生了什么或没有提供您收到的消息错误的信息,这是我能给您的最佳答案。请发布更多信息,我很乐意编辑。
推荐阅读
- python - Ortools - Jobshop - 根据他们在机器上的排名修改任务持续时间
- docker - Docker Spark 3.0.0 pyspark py4j.protocol.Py4JError
- http - 使用 RestSharp 基本身份验证使用 web api 返回 null
- r - 了解异常消息
- powerbi - 如何从 powerbi 调用 CRM 操作
- reactjs - React:获取组件外部映射项的索引
- javascript - 第三方 API 需要访问 React 应用中的状态
- html - 在 html 选择中悬停或选择项目时,如何避免更改背景颜色?
- asp.net-mvc - IdentityModel vs Microsoft.IdentityModel vs System.IdentityModel
- flutter - Dart/Flutter - 仅保留列表中的重复项