php - 如何重定向到登录页面然后重定向回php中的上一页

标签 php mysql authentication redirect require

我知道对此有很多问题,但当我希望登录始终重定向到主页时,我找不到答案,除非用户单击“提交”页面,它应该登录然后允许用户添加建议。 单击“提交”页面后,我设法重定向到登录页面,但之后,它重定向到主页,我陷入了循环。 (索引是我的主页)。 (建议是我想强制登录的地方)。 这是我到目前为止所做的: 在我的 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/

相关文章:

php - 加载 php 文件算作 HTTP 请求吗?

php - 将随机字符附加到用户上传照片的末尾

mysql - 如何使用 sql 查询对列表列表进行排序?

python - 为 MySQL View 创建模型并加入它

authentication - 我刚刚了解到 JWT 的缺点 - 有什么替代方案?

Android 应用程序持久身份验证

php - 无法通过 Mock 测试

php - 排序 multidim 数组 : prioritize if column contains substring, 然后按第二列排序

javascript - 在页面的上端显示 'Available in AppStore too'

rest - 如何在没有用户交互的情况下向 Azure Active Directory 进行身份验证?