繁体   English   中英

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

[英]how to redirect to login page then redirect back to the previous page in php

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

<?php
if(!isset($_SESSION['user_id'])) 
{
    $_SESSION["login_redirect"] = $_SERVER["PHP_SELF"];
    header("Location: login2.php");
    exit;
}
?>

登录-form.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(); 在每一页的第一行,实际上之前没有任何空格或换行符!

暂无
暂无

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

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