运行登录脚本后重定向到上一页上一页(不同的页面运行相同的脚本,但希望重定向到正确的页面)。

问题描述 投票:0回答:1

对不起,如果这是一个简单的问题,但我是一个新的PHP新手!我有一个 "头 "文件,它是我的网站中所有页面的导航栏,通过require语句。

我有一个 "头 "文件,它是我网站所有页面的导航栏,通过require语句. 这个导航栏的一部分被设置为根据用户是否登录来显示登录退出按钮。当用户提交表单时,数据会被发送到一个php文件中,如果有错误,请求会被发回(字段已完成),或者有一个头到索引页。

问题是,我想让页眉指向上一个页面(不是需要的页眉文件,而是主网页。我想过在 "require "所在的php标签里加一些东西,但似乎没有用。

有人有什么办法吗?我只发送相关区域的代码,因为这些都是大页面!

内容标题.php

<DOCTYPE! html style="scroll-behavious: smooth;">

    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <?php

        if(basename(__FILE__).PHP_EOL == '/J277_01/1.1.1/J277_performance') {
            echo '<title>1.1.1</title>';
          } else {
            echo "<title>Learn Don't 4Get</title>";
          };

        ?>


        <!--Stylesheets-->
        <link rel="stylesheet" href="../../../css/reset.css"><!--Reset to defaults-->
        <link rel="stylesheet" href="../../../css/demo.css">
        <link rel="stylesheet" href="../../../css/index.css"><!--Make Sign in form work-->
        <link rel="stylesheet" href="../../../css/header.css"><!--Nav bar-->
        <link href="../../../CSS/course.css?ts=<?=time()?>" rel="stylesheet" type="text/css"> <!--Course content stylesheet-->

        <!--Fonts-->
        <link href="https://fonts.googleapis.com/css?family=Play" rel="stylesheet">
        <link href="https://fonts.googleapis.com/css2?family=Exo:wght@700&display=swap" rel="stylesheet">


    </head>

    <body>
        <header class="cd-main-header">
            <div class="cd-main-header__logo">
                <a href="#0"><img src="../../../img/logo2.png" alt="Logo"></a>
            </div>

            <nav class="cd-main-nav js-main-nav">
                <ul class="cd-main-nav__list js-signin-modal-trigger">
                    <li><a class="cd-main-nav__item" href="#0">About</a></li>
                    <li><a class="cd-main-nav__item" href="#0">News</a></li>
                    <li><a class="cd-main-nav__item" href="#0">Resources</a></li>
                    <li><a class="cd-main-nav__item" href="../../../course.php">Specification</a></li>
                    <li><a class="cd-main-nav__item" href="#0">Contact</a></li>
                    <?php 
                    session_start();
                    if (!isset($_SESSION['id'])) {
                        echo '
                        <li><a class="cd-main-nav__item cd-main-nav__item--signin" href="#0" data-signin="login">Sign in</a></li>
                        <li><a class="cd-main-nav__item cd-main-nav__item--signup" href="#0" data-signin="signup">Sign up</a></li>';
                    } else{
                        echo'<li></li><li><form action="includes/logout.inc.php" method="post"><button class="cd-main-nav__item cd-main-nav__item--logout" type="submit" name="course">Log Out</button></form></li>';
                    }

                    ?>
                </ul>
            </nav>
        </header>

        <div class="cd-signin-modal js-signin-modal">
        <!-- this is the entire modal form, including the background -->
        <div class="cd-signin-modal__container">
            <!-- this is the container wrapper -->
            <ul class="cd-signin-modal__switcher js-signin-modal-switcher js-signin-modal-trigger">
                <li><a href="#0" data-signin="login" id="login-switcher" data-type="login">Sign in</a></li>
                <li><a href="#0" data-signin="signup" id="signup-switcher" data-type="signup">Create an Account</a></li>
            </ul>

            <div class="cd-signin-modal__block js-signin-modal-block" data-type="login">
                <!-- log in form -->
                <form class="cd-signin-modal__form" id="login-form" action="../../../includes/login.inc.php" method="post">
                    <p class="cd-signin-modal__fieldset">
                        <label class="cd-signin-modal__label cd-signin-modal__label--email cd-signin-modal__label--image-replace" for="signin-email">E-mail</label>
                        <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border mailuidfield" id="signin-email" type="email" name="mailuid" placeholder="Username or E-mail">
                        <span class="cd-signin-modal__error" id="login-mailuid">Error message here!</span>
                    </p>

                    <p class="cd-signin-modal__fieldset">
                        <label class="cd-signin-modal__label cd-signin-modal__label--password cd-signin-modal__label--image-replace" for="signin-password">Password</label>
                        <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border pwdfield" id="signin-password" type="text" name="pwd" placeholder="Password">
                        <a href="#0" class="cd-signin-modal__hide-password js-hide-password">Hide</a>
                        <span class="cd-signin-modal__error" id="login-pwd">Error message here!</span>
                    </p>

                    <p class="cd-signin-modal__fieldset">
                        <input type="checkbox" id="remember-me" checked class="cd-signin-modal__input ">
                        <label for="remember-me">Remember me</label>
                    </p>

                    <p class="cd-signin-modal__fieldset">
                        <input class="cd-signin-modal__input cd-signin-modal__input--full-width" name="login-submit" type="submit" value="Login">
                    </p>
                </form>

                <p class="cd-signin-modal__bottom-message js-signin-modal-trigger"><a href="#0" data-signin="reset">Forgot your password?</a></p>
            </div>
            <!-- cd-signin-modal__block -->

            <div class="cd-signin-modal__block js-signin-modal-block" data-type="signup">
                <!-- sign up form -->
                <form class="cd-signin-modal__form" id="signup-form" action="../../../includes/signup.inc.php" method="post">
                    <p class="cd-signin-modal__fieldset">
                        <label class="cd-signin-modal__label cd-signin-modal__label--name cd-signin-modal__label--image-replace" for="signup-first">First Name</label>
                        <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border" id="signup-first" type="text" name="first" placeholder="First Name">
                        <span class="cd-signin-modal__error" id="firstfield">Error message here!</span>
                    </p>

                    <p class="cd-signin-modal__fieldset">
                        <label class="cd-signin-modal__label cd-signin-modal__label--name cd-signin-modal__label--image-replace" for="signup-last">Last Name</label>
                        <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border" id="signup-last" type="text" name="last" placeholder="Surname">
                        <span class="cd-signin-modal__error" id="lastfield">Error message here!</span>
                    </p>

                    <p class="cd-signin-modal__fieldset">
                        <label class="cd-signin-modal__label cd-signin-modal__label--username cd-signin-modal__label--image-replace" for="signup-username">Username</label>
                        <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border" id="signup-uid" type="text" name="uid" placeholder="Username">
                        <span class="cd-signin-modal__error" id="uidfield">Error message here!</span>
                    </p>

                    <p class="cd-signin-modal__fieldset">
                        <label class="cd-signin-modal__label cd-signin-modal__label--email cd-signin-modal__label--image-replace" for="signup-email">E-mail</label>
                        <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border" id="signup-mail" type="email" name="mail" placeholder="E-mail">
                        <span class="cd-signin-modal__error" id="mailfield">Error message here!</span>
                    </p>

                    <p class="cd-signin-modal__fieldset">
                        <label class="cd-signin-modal__label cd-signin-modal__label--password cd-signin-modal__label--image-replace" for="signup-password">Password</label>
                        <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border" id="signup-pwd" type="text" name="pwd" placeholder="Password">
                        <a href="#0" class="cd-signin-modal__hide-password js-hide-password">Hide</a>
                        <span class="cd-signin-modal__error" id="pwdfield">Error message here!</span>
                    </p>

                    <p class="cd-signin-modal__fieldset">
                        <input type="checkbox" id="accept-terms" class="cd-signin-modal__input ">
                        <label for="accept-terms">I agree to the <a href="#0">Terms</a></label>
                        <span class="cd-signin-modal__error" id="terms-error">Please accept the Terms!</span>
                    </p>
                    <p class="cd-signin-modal__fieldset">
                    <div id="signupbuttoncheck"><input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding"  name="signup-submit" id="signupbutton" type="submit" value="Create account" disabled></div>
                    </p>

                    <script>
                    //SignupButtonActive
                        var terms = document.getElementById("accept-terms");
                        var submit = document.getElementById("signupbuttoncheck");
                        terms.addEventListener("click", function(){
                            if (terms.checked){
                                console.log("checked")
                                document.getElementById("signupbutton").disabled = false;
                            } else {
                                document.getElementById("signupbutton").disabled = true;

                            }
                        });
                        submit.addEventListener("click", function(){
                            //if (!terms.checked){
                                document.querySelector("#terms-error").classList.add("cd-signin-modal__error--is-visible");
                                console.log("hello");
                            //};
                        });

                    </script> 
                </form>
            </div>
            <!-- cd-signin-modal__block -->

            <div class="cd-signin-modal__block js-signin-modal-block" data-type="reset">
                <!-- reset password form -->
                <p class="cd-signin-modal__message">Lost your password? Please enter your email address. You will receive a link to create a new password.</p>

                <form class="cd-signin-modal__form">
                    <p class="cd-signin-modal__fieldset">
                        <label class="cd-signin-modal__label cd-signin-modal__label--email cd-signin-modal__label--image-replace" for="reset-email">E-mail</label>
                        <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding cd-signin-modal__input--has-border" id="reset-email" type="email" placeholder="E-mail">
                        <span class="cd-signin-modal__error">Error message here!</span>
                    </p>

                    <p class="cd-signin-modal__fieldset">
                        <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding" type="submit" value="Reset password">
                    </p>
                </form>

                <p class="cd-signin-modal__bottom-message js-signin-modal-trigger"><a href="#0" data-signin="login">Back to log-in</a></p>
            </div>

            <!-- cd-signin-modal__block -->
            <a href="#0" class="cd-signin-modal__close js-close">Close</a>
            <div class="cd-signin-modal__block js-signin-modal-block" data-type="success">
                <h1> Success! </h1>
                <p class="cd-signin-modal__message">You have successfully created an account and are now able to sign in to Learn Don't 4Get!</p>

                <form class="cd-signin-modal__form">
                    <p class="cd-signin-modal__fieldset">
                        <input class="cd-signin-modal__input cd-signin-modal__input--full-width cd-signin-modal__input--has-padding" type="button" id="back-to-login" value="Sign in">
                    </p>
                </form>
            </div>
        </div>
        <!-- cd-signin-modal__container -->
    </div>

这就显示了导航栏,我有一个JS函数,当按钮被点击时,显示一个模式。

登录验证表单,位于includes文件夹内。

<?php

// Here we check whether the user got to this page by clicking the proper login button.
if (isset($_POST['login-submit'])) {

  // We include the connection script so we can use it later.
  // We don't have to close the MySQLi connection since it is done automatically, but it is a good habit to do so anyways since this will immediately return resources to PHP and MySQL, which can improve performance.
  require 'dbh.inc.php';

  // We grab all the data which we passed from the signup form so we can use it later.
  $mailuid = $_POST['mailuid'];
  $password = $_POST['pwd'];

  // Then we perform a bit of error handling to make sure we catch any errors made by the user. Here you can add ANY error checks you might think of! I'm just checking for a few common errors in this tutorial so feel free to add more. If we do run into an error we need to stop the rest of the script from running, and take the user back to the login form with an error message.

  // We check for any empty inputs. (PS: This is where most people get errors because of typos! Check that your code is identical to mine. Including missing parenthesis!)
  if (empty($mailuid) || empty($password)) {
    header("Location: ../new-index.php?loginerror=emptyfields&mailuid=".$mailuid);
    exit();
  }
  else {

    // If we got to this point, it means the user didn't make an error! :)

    // Next we need to get the password from the user in the database that has the same username as what the user typed in, and then we need to de-hash it and check if it matches the password the user typed into the login form.

    // We will connect to the database using prepared statements which work by us sending SQL to the database first, and then later we fill in the placeholders by sending the users data.
    $sql = "SELECT * FROM users WHERE uidUsers=? OR emailUsers=?;";
    // Here we initialize a new statement using the connection from the dbh.inc.php file.
    $stmt = mysqli_stmt_init($conn);
    // Then we prepare our SQL statement AND check if there are any errors with it.
    if (!mysqli_stmt_prepare($stmt, $sql)) {
      // If there is an error we send the user back to the signup page.
      header("Location: ../new-index.php?loginerror=sqlerror&mailuid=");
      exit();
    }
    else {

      // If there is no error then we continue the script!

      // Next we need to bind the type of parameters we expect to pass into the statement, and bind the data from the user.
      mysqli_stmt_bind_param($stmt, "ss", $mailuid, $mailuid);
      // Then we execute the prepared statement and send it to the database!
      mysqli_stmt_execute($stmt);
      // And we get the result from the statement.
      $result = mysqli_stmt_get_result($stmt);
      // Then we store the result into a variable.
      if ($row = mysqli_fetch_assoc($result)) {
        // Then we match the password from the database with the password the user submitted. The result is returned as a boolean.
        $pwdCheck = password_verify($password, $row['pwdUsers']);
        // If they don't match then we create an error message!
        if ($pwdCheck == false) {
          // If there is an error we send the user back to the signup page.
          header("Location: ../new-index.php?loginerror=wrongpwd&mailuid=".$mailuid);
          exit();
        }
        // Then if they DO match, then we know it is the correct user that is trying to log in!
        else if ($pwdCheck == true) {

          // Next we need to create session variables based on the users information from the database. If these session variables exist, then the website will know that the user is logged in.

          // Now that we have the database data, we need to store them in session variables which are a type of variables that we can use on all pages that has a session running in it.
          // This means we NEED to start a session HERE to be able to create the variables!
          session_start();
          // And NOW we create the session variables.
          $_SESSION['id'] = $row['idUsers'];
          $_SESSION['uid'] = $row['uidUsers'];
          $_SESSION['email'] = $row['emailUsers'];
          // Now the user is registered as logged in and we can now take them back to the front page! :)
          header("Location: ../new-index.php?login=success");
          exit();
        }
      }
      else {
        header("Location: ../new-index.php?loginerror=wronguidpwd&mailuid=");
        exit();
      }
    }
  }
  // Then we close the prepared statement and the database connection!
  mysqli_stmt_close($stmt);
  mysqli_close($conn);
}
else {
  // If the user tries to access this page an inproper way, we send them back to the signup page.
  header("Location: ../new-index.php");
  exit();
}

本质上来说,我希望它不是指向 "new-index.php",而是指向错误,但指向它被调用的页面。

谢谢!如果这是个很明显的问题,我很抱歉。对不起,如果这是显而易见的,我似乎不能让它工作!.......

EDIT: 这里是我目前的文件,你可以看看发生了什么。

数据库连接 - dbh.inc.php


<?php
$dBServername = "localhost";
$dbuser = "root";
$userpw = "";
$database = "userdata";

// Create connection
$conn = mysqli_connect($dBServername, $dbuser, $userpw, $database);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

$password = password_hash("test", PASSWORD_DEFAULT);
echo $password;

登录.php

<?php
//login.php
require('dbh.inc.php');
$datetime = date("U");

 $obj = new stdClass();
     $obj->login = FALSE;  //initialized
     $obj->email = '';
     $obj->datetime = $datetime;
     $obj->dateread = date("D M j G:i:s T Y");

$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

  if(!($password=@$_POST["password"])){$obj->error = 'No password included.'; echo json_encode($obj); exit;}
  else {$password=$_POST["password"];}

  if(!($email=@$_POST["email"])){$obj->error = 'No email included.'; echo json_encode($obj); exit;}
  else {$email=$_POST["email"];}

      if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
          $obj->error = 'Invalid Email Address.';
          echo json_encode($obj);
          exit;
           }

 $db = new mysqli('localhost', $dbuser, $userpw, $database);   //These values kept in your conf.php file
 if (mysqli_connect_errno()) {
                             $obj->error = 'Error: Could not connect to database.';
                             error_log(json_encode($obj));
                             echo json_encode($obj);
                             exit;
                             }

 $query = "SELECT email, passwordHash              //A password hash created by password_hash()
           FROM users WHERE email = ?";
 $stmt = $db->prepare($query);
 $stmt->bind_param('s', $email);
 $stmt->execute();
 $stmt->store_result();
 $stmt->bind_result($emaildb, $passworddb);
 if (mysqli_connect_errno()) {$obj->error = 'Error: Could not connect to database.  ';
                             error_log(json_encode($obj));
                             echo json_encode($obj);
                             exit;
 }
 else{
     if($stmt->num_rows == 1) {
          while($stmt->fetch()){ 
             $obj->email = $emaildb;
             $obj->passwordHash = $passworddb;
          }

     } elseif($stmt->num_rows == 0) {
          $obj->error = 'No matching credentials found.';
          echo json_encode($obj);
          exit;
     }
}
$stmt->close();

if(password_verify($password , $obj->passwordHash)){
    $obj->login = 'success';
    echo json_encode($obj);
}

$db->close();
exit;
?>

登录.html

<div id="formInputs">
    <p>
        <input type="text" name="email" id="email" style="width:67%;" placeholder="Email*" />
        <input type="password" name="password" id="password" style="width:67%;" placeholder="Password*" />
    </p>
    <button id="reviewButton" onclick="login()" class="buttonLogin">Log In</button>
</div>

<div id="for-logged-in-user-only" style="display:none;"></div>
<p id="result"></p>



<script>
    function login() {

        var email = encodeURIComponent(document.getElementById("email").value);
        var password = encodeURIComponent(document.getElementById("password").value);

        var params = "email=" + email + "&password=" + password;

        var xhttp = new XMLHttpRequest();
        xhttp.onreadystatechange = function() {
            if (this.readyState == 4 && this.status == 200) {

                document.getElementById("result").innerHTML = 'Checking Credentials....';
                document.getElementById("result").innerHTML = this.responseText;
                console.log(this.responseText);
                var response = JSON.parse(this.responseText);

                if (response.hasOwnProperty('error')) {
                    document.getElementById("result").innerHTML = response.error;
                } else {
                    var login = response.login;
                    if (login == "success") {
                        document.getElementById("for-logged-in-user-only").style.display = "inline";
                        document.getElementById("for-logged-in-user-only").innerHTML = "Only a logged-in user will see this after logging in.";
                        document.getElementById("formInputs").style.display = "none"; //hides the login form inputs                  
                    }
                }
            } else {
                window.setTimeout(failed(), 3000);
            }
        };
        xhttp.open("POST", "login.php", true);
        xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        xhttp.send(params);
    }


    function failed() {
        document.getElementById("result").innerHTML = 'Failed connection.';
    }
</script>
php authentication session redirect header
1个回答
0
投票

虽然我很想能够用PHP来完成所有的事情。 但是Javascript是你需要熟悉的另一个部分,以便对客户端进行这样的控制。 具体来说,异步Javascript允许当前页面与你的PHP脚本进行交互,而所有的脚本都停留在该页面上。 要做到这一点,你将摆脱你的 "form action=......",而使用 "button"。",而是使用 "button onclick= aFunction()...。"来执行一个函数,该函数从你的输入中抓取值,并将它们发布到你的PHP中,并从该PHP文件中获取结果,而浏览器则坐在同一个地方。 下面是它的要点。

<div id="formInputs">
<p>
<input type="text" name="email" id="email" style="width:67%;" placeholder="Email*"/>  
<input type="password" name="password" id="password" style="width:67%;" placeholder="Password*"/>
</p>
<button id="reviewButton" onclick="login()" class="buttonLogin">Log In</button>
</div>

<div id="for-logged-in-user-only" style="display:none;"></div>
<p id="result"></p>



<script>

    function login() {

      var email = encodeURIComponent(document.getElementById("email").value);
      var password = encodeURIComponent(document.getElementById("password").value); 

      var params = "email="+email+"&password="+password;  

      var xhttp = new XMLHttpRequest();
      xhttp.onreadystatechange = function() {
        if (this.readyState == 4 && this.status == 200) {

            document.getElementById("result").innerHTML = 'Checking Credentials....';
            console.log(this.responseText);
            var response = JSON.parse(this.responseText);

            if(response.hasOwnProperty('error')){
                document.getElementById("result").innerHTML = response.error;
            }else{
                if(response.login == "success"){
                    document.getElementById("for-logged-in-user-only").style.display = "inline";
                    document.getElementById("for-logged-in-user-only").innerHTML = "Only a logged-in user will see this after logging in.";
                    document.getElementById("formInputs").style.display = "none";   //hides the login form inputs                  
                }
            }
        }else{
          window.setTimeout(failed(), 3000);
        }
      };
      xhttp.open("POST", "login.php", true);
      xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
      xhttp.send(params);
    }


    function failed(){
          document.getElementById("result").innerHTML = 'Failed connection.';
    }

</script>

而你的PHP文件将看起来像这样:

<?php
//login.php
require('/path/to/conf.php');
$datetime = date("U");

 $obj = new stdClass();
     $obj->login = FALSE;  //initialized
     $obj->email = '';
     $obj->datetime = $datetime;
     $obj->dateread = date("D M j G:i:s T Y");

$_POST  = filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING);

  if(!($password=@$_POST["password"])){$obj->error = 'No password included.'; echo json_encode($obj); exit;}
  else {$password=$_POST["password"];}

  if(!($email=@$_POST["email"])){$obj->error = 'No email included.'; echo json_encode($obj); exit;}
  else {$email=$_POST["email"];}

      if(!filter_var($email, FILTER_VALIDATE_EMAIL)){
          $obj->error = 'Invalid Email Address.';
          echo json_encode($obj);
          exit;
           }

 $db = new mysqli('localhost', $dbuser, $userpw, $database);   //These values kept in your conf.php file
 if (mysqli_connect_errno()) {
                             $obj->error = 'Error: Could not connect to database.';
                             error_log(json_encode($obj));
                             echo json_encode($obj);
                             exit;
                             }

 $query = "SELECT email, passwordHash              
           FROM users WHERE email = ?";   //A password hash created by password_hash()
 $stmt = $db->prepare($query);
 $stmt->bind_param('s', $email);
 $stmt->execute();
 $stmt->store_result();
 $stmt->bind_result($emaildb, $passworddb);
 if (mysqli_connect_errno()) {$obj->error = 'Error: Could not connect to database.  ';
                             error_log(json_encode($obj));
                             echo json_encode($obj);
                             exit;
 }
 else{
     if($stmt->num_rows == 1) {
          while($stmt->fetch()){ 
             $obj->email = $emaildb;
             $obj->passwordHash = $passworddb;
          }

     } else($stmt->num_rows == 0) {
          $obj->error = 'No matching credentials found.';
          echo json_encode($obj);
          exit;
     }
}
$stmt->close();

if(password_verify($password , $obj->passwordHash)){
    $obj->login = 'success';
    echo json_encode($obj);
}

$db->close();
exit;
?>

说白了,你的conf.php文件可以像这样简单。

pathtoconf.php

<?php
//conf.php

//For Database
$dbuser='username';
$userpw='strongPassword';
$database='nameofDatabase';

?>
© www.soinside.com 2019 - 2024. All rights reserved.