0

I've been following Dani Krossings Login System It's a great tutorial and is just what I am looking for, there is just one thing I'm struggling with.

After logging in, the header doesn't refresh. Following login, the header should change to ...Profile Page, Logout. The code I have stays as Sign Up, Login. It is as is the $_SESSION variable has not come through to the header. However, if after login, I select the Sign up or login link, the header changes to what it should be.

Function code

function uidExists($conn, $username) {
  $sql = "SELECT * FROM users WHERE usersUid = ? OR usersEmail = ?;";
    $stmt = mysqli_stmt_init($conn);
    if (!mysqli_stmt_prepare($stmt, $sql)) {
        header("location: ../signup.php?error=stmtfailed");
        exit();
    }

    mysqli_stmt_bind_param($stmt, "ss", $username, $username);
    mysqli_stmt_execute($stmt);

    // "Get result" returns the results from a prepared statement
    $resultData = mysqli_stmt_get_result($stmt);

    if ($row = mysqli_fetch_assoc($resultData)) {
        return $row;
    }
    else {
        $result = false;
        return $result;
    }

    mysqli_stmt_close($stmt);
}

function loginUser($conn, $username, $pwd) {
    $uidExists = uidExists($conn, $username);

    if ($uidExists === false) {
        header("location: ../login.php?error=wronglogin");
        exit();
    }

    $pwdHashed = $uidExists["usersPwd"];
    $checkPwd = password_verify($pwd, $pwdHashed);

    if ($checkPwd === false) {
        header("location: ../login.php?error=wronglogin");
        exit();
    }
    elseif ($checkPwd === true) {
        session_start();
        $_SESSION["userid"] = $uidExists["usersId"];
        $_SESSION["useruid"] = $uidExists["usersUid"];
        header("location: ../index.php?error=none");
        exit();
    }
}

header.php

<?php
  session_start();
  include_once 'includes/functions.inc.php';
?>

<!DOCTYPE html>
<html lang="en" dir="ltr">
  <head>
    <meta charset="utf-8">
    <title>PHP Project 01</title>
    <!--I won't do more than barebone HTML, since this isn't an HTML tutorial.-->
    <link href="https://fonts.googleapis.com/css2?family=Roboto:ital,wght@0,100;0,300;0,400;0,500;0,700;0,900;1,100;1,300;1,400;1,500;1,700;1,900&display=swap" rel="stylesheet">
    <link rel="stylesheet" href="css/reset.css">
    <link rel="stylesheet" href="css/style.css">
  </head>
  <body>

    <!--A quick navigation-->
    <nav>
      <div class="wrapper">
        <a href="index.php"><img src="img/logo-white.png" alt="Blogs logo"></a>
        <ul>
          <li><a href="index.php">Home</a></li>
          <li><a href="discover.php">About Us</a></li>
          <li><a href="blog.php">Find Blogs</a></li>
          <?php
            if (isset($_SESSION["useruid"])) {
              echo "<li><a href='profile.php'>Profile Page</a></li>";
              echo "<li><a href='logout.php'>Logout</a></li>";
            }
            else {
              echo "<li><a href='signup.php'>Sign up</a></li>";
              echo "<li><a href='login.php'>Log in</a></li>";
            }
          ?>
        </ul>
      </div>
    </nav>

<!--A quick wrapper to align the content (ends in footer.php)-->
<div class="wrapper">

Login.php

<?php
include_once 'header.php';

?>

<section class="signup-form">
  <h2>Log In</h2>
  <div class="signup-form-form">
    <form action="includes/login.inc.php" method="post">
      <input type="text" name="uid" placeholder="Username/Email...">
      <input type="password" name="pwd" placeholder="Password...">
      <button type="submit" name="submit">Sign up</button>
    </form>
  </div>
  <?php
    // Error messages
    if (isset($_GET["error"])) {
      if ($_GET["error"] == "emptyinput") {
        echo "<p>Fill in all fields!</p>";
      }
      else if ($_GET["error"] == "wronglogin") {
        echo "<p>Wrong login!</p>";
      }
    }
  ?>
</section>

<?php
  include_once 'footer.php';
?>

login.inc.php

<?php

if (isset($_POST["submit"])) {

  // First we get the form data from the URL
  $username = $_POST["uid"];
  $pwd = $_POST["pwd"];

  // Then we run a bunch of error handlers to catch any user mistakes we can (you can add more than I did)
  // These functions can be found in functions.inc.php

  require_once 'dbh.inc.php';
  require_once 'functions.inc.php';

  // Left inputs empty
  if (emptyInputLogin($username, $pwd) === true) {
    header("location: ../login.php?error=emptyinput");
        exit();
  }

  // If we get to here, it means there are no user errors

  // Now we insert the user into the database
  loginUser($conn, $username, $pwd);

} else {
    header("location: ../login.php");
    exit();
}

Anyone have any thoughts on how I can get the header to refresh on submission of a successful login form?

Matt Drake
  • 144
  • 8
  • 2
    Have you got error reporting turned on? Are you getting any errors? – fubar May 24 '21 at 02:27
  • Sorry, how would I do that. New to alot of this. – Matt Drake May 24 '21 at 02:36
  • 1
    See [How can I get useful error messages in PHP?](https://stackoverflow.com/questions/845021/how-can-i-get-useful-error-messages-in-php) – Phil May 24 '21 at 02:39
  • You're probably calling `include_once 'header.php';` before `loginUser()`. But since the code you showed in your example doesn't show where you call `loginUser()` it's really hard to tell. – kmoser May 24 '21 at 02:44
  • I've edited the post to show the login.inc.php code. Will take a look at the error reporting also. Thank you – Matt Drake May 24 '21 at 02:49
  • I think that is my bad pasting into the post but will check – Matt Drake May 24 '21 at 03:02
  • Where is this being set? $uidExists["usersUid"]; isset returns false on null – Vbudo May 24 '21 at 03:03
  • @Vbudo edited post with $uidExists function code – Matt Drake May 24 '21 at 03:15
  • FYI `mysqli_stmt_close($stmt);` in `uidExists()` will **never** run since you `return` before it gets to that line. This may or may not be a problem. I suggest you follow the advice in [this answer](https://stackoverflow.com/a/22662582/283366) to make sure you see any and all errors, especially ones from MySQLi – Phil May 24 '21 at 03:33

2 Answers2

-1

Since Sometimes Some Content Is Left On The Page After Reloading The Header, We Need To Use die() after Changing Location From Header.

TBH, Redirecting Using PHP Is Not Recommended, I Suggest You To Redirect The User Using An Inbuilt JavaScript Function, window.location.replace(path)

You Can Call It Inside A PHP Script Using

  ?>
    <script>
      window.location.replace(path)
    </script>
  <?php

Or Simply Just Create Your Own Function:

function redirect($path) {
  ?>
    <script>
      window.location.replace('<?php echo $path ?>')
    </script>
  <?php
}

And Use It: redirect("profile.php")

Dharman
  • 30,962
  • 25
  • 85
  • 135
  • I really feel like redirecting via client-side code is not a great idea. The 30x response status exists for a reason. Your solution requires producing an entire, valid HTML document just to inject a ` – Phil May 24 '21 at 03:21
  • @Phil I Feel So Too but have been using it for much time without any problem.. – Albert Logic Einstein May 24 '21 at 03:38
  • The [Post/Redirect/Get](https://en.wikipedia.org/wiki/Post/Redirect/Get) pattern is well established – Phil May 24 '21 at 03:39
-1

Always put a session_start() into every page I want to use $_SESSION variables.

Fixed.

Thanks for all your help!

Matt Drake
  • 144
  • 8