0

sorry if this is a simple question, but I am new to php!

I have a "header" file which is the nav bar for all of the pages in my website, through the require statement. A part of this nav bar is set to either show login/ logout buttons dependent on whether the user is logged in. When the user submits the form, the data is sent to a php file, and if there's an error, the request is sent back (with fields completed), or there's a header to the index page.

The issue is, I want the header to be to the previous page (not the required header file, but the main webpage. I thought of putting something inside the php tags where the "require" is, but that didn't seem to work.

Does anyone have any ideas? I will only send the relevant areas of code as these are big pages!

content-header.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>

That shows the nav bar, and I have a JS function that displays a modal when the buttons are clicked.

The login verification form, located inside includes folder:

<?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();
}

Essentially, instead of hearing to "new-index.php", I want it to do the exact same with the errors, but to the page in which it's called from.

Thanks! Sorry if this is blatantly obvious, I can't seem to get it to work! . . . . . .

EDIT: here are my files currently so you can see what's going on:

Database connection - 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;

login.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;
?>

login.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>
  • Not clear what you're looking for. You want to stay on the same page if the login fails, so that the user can try again? Or, you want successful logins to redirect to your home page? – Adam Winter May 25 '20 at 02:49
  • Or you're trying to make it so that users resume where they were before you forced them to the login page? – Adam Winter May 25 '20 at 02:58
  • So say you are on one of the content pages (lets call it content.php). At the top of the content page, there is a "require(header.php)" which has the navigation bar for all the pages. In this navigation bar, there is a log in/ log out button, which when pressed causes a modal login box to appear on the page (content.php). – James Duxbury May 25 '20 at 14:58
  • When the user presses "log in" (the same happens for sign up but we will ignore that for now), the contents of the form are sent to the login script (login.inc.php), where the login data is validated. – James Duxbury May 25 '20 at 15:00
  • If there is an error, there is a header back to the content.php file, where the modal box is displayed with the relevant error. If there isn't an error, a session called 'id" starts, the data is written to a db and there is a header back to the content.php file, where the sign in button is now a log in. – James Duxbury May 25 '20 at 15:02
  • All this works, but I can only get it to go back to index.php (the file I created this on),as all the headers in login.inc.php point to index.php. I want the headers to go to the page the user was initially on (content.php) instead of index.php every time, but I don't know how to do this without making a whole new login form for each page, which is clearly unnecessary! Does this help? @AdamWinter – James Duxbury May 25 '20 at 15:04
  • Answered below. Also, using header() isn't considered the best way to do redirect. See https://stackoverflow.com/questions/200337/whats-the-best-way-to-automatically-redirect-someone-to-another-webpage – Adam Winter May 25 '20 at 18:33

1 Answers1

0

As much as I'd love to be able to just do everything with PHP. Javascript is really the other part of the equation that you need to be familiar with in order have that kind of control over the client side. Specifically, Asynchronous Javascript allows the current page to interact with your PHP scripts all while staying on that page. To do this, you will get rid of your "form action=.... " and, instead, use "button onclick= aFunction().... " to execute a function that grabs the values from your inputs and posts them to your PHP and gets a result from that PHP file all while the browser sits in the same place. The following is the gist of it:

<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>

And your PHP file will look something like this:

<?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;
?>

To be clear, you conf.php file could be as simple as this:

/path/to/conf.php

<?php
//conf.php

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

?>
Adam Winter
  • 1,680
  • 1
  • 12
  • 26
  • Comments are not for extended discussion; this conversation has been [moved to chat](https://chat.stackoverflow.com/rooms/215012/discussion-on-answer-by-adam-winter-redirect-to-the-previous-page-previous-page). – Samuel Liew May 31 '20 at 04:37