我知道对此有很多问题,但当我希望登录始终重定向到主页时,我找不到答案,除非用户单击“提交”页面,它应该登录然后允许用户添加建议。 单击“提交”页面后,我设法重定向到登录页面,但之后,它重定向到主页,我陷入了循环。 (索引是我的主页)。 (建议是我想强制登录的地方)。 这是我到目前为止所做的: 在我的 suggest.php 的顶部:
<?php
if(!isset($_SESSION['user_id']))
{
$_SESSION["login_redirect"] = $_SERVER["PHP_SELF"];
header("Location: login2.php");
exit;
}
?>
登录表单.php:
<?php
if(isset($_POST['loginbutton'])){
require 'dbh.inc.php';
$UsernameEmail = $_POST['username/email'];
$password = $_POST['password'];
if (empty($UsernameEmail)||empty($password)){
header("location: ../Index.php?error=emptyfields&username");
exit();
}else {
$sql = "SELECT * FROM users WHERE username=? OR email =? ;" ;
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt,$sql)){
header("location: ../Index.php?error=sqlerror");
exit();
}
else {
mysqli_stmt_bind_param($stmt , "ss", $UsernameEmail,$UsernameEmail );
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
if($row = mysqli_fetch_assoc($result)){
$pwdCheck = password_verify($password , $row['password']);
if($pwdCheck == false ){
header("location: ../Index.php?error=wrongPassword");
exit();
} else if ($pwdCheck == true ){
session_start();
$_SESSION['user_id']= $row['id'];
$_SESSION['user_name']= $row['username'];
} else {
header("location: ../Index.php?error=wrongPassword");
exit();
}
}
else {
header("location: ../Index.php?nouser/emailmatch");
exit();
}
}
}
}
else {
header("Location: ../Index.php?succses");
exit();
}
我还在 SUGGEST.php 中尝试了这段代码
<?php
if(!isset($_SESSION['user_id']))
{
header('Location: login2.php?redirect=SUGGEST.php');
exit;
}
?>
这个在login-form.php中,但也不起作用
if (isset($_GET['redirect'])) {
header('Location: ' . $_GET['redirect']);
}
这是我第一次用 php 编码,所以我真的很想得到一个详细的答案。 谢谢您
最佳答案
您应该在每个页面的第一行处使用session_start();
,实际上之前没有任何空格或换行!
关于php - 如何重定向到登录页面然后重定向回php中的上一页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59143618/