0

EDITED

I try to create registration system where users stay loggedin after successful registration. I tried to create a session and insert it to inside registration.php to the part where I am trying to redirecting to login page. The system works fine (It's create MYSQL record and everything works). Is there any way how to be 100% sure that user is loggedin some sort of command into console or something like that.

How it works right now:

  1. User signed up.
  2. Redirecting to home page and user must be loggedin.

registration.php:

<?php
// Include config file
require_once "config/config.php";

// Define variables and initialize with empty values
$username = $password = $confirm_password = $email = "";
$username_err = $password_err = $confirm_password_err = $email_err = "";

// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){

// Validate email
  if(empty(trim($_POST["email"]))){
    $email_err  = "Email is required.";
  } else{
    // Prepare a select statement
    $sql = "SELECT id FROM users WHERE email = ?";

    if($stmt = mysqli_prepare($link, $sql)){
      // Bind variables to the prepared statement as parameters
      mysqli_stmt_bind_param($stmt, "s", $param_email);

      // Set parameters
      $param_email = trim($_POST["email"]);

      // Attempt to execute the prepared statement
      if(mysqli_stmt_execute($stmt)){
        /* store result */
        mysqli_stmt_store_result($stmt);

        if(mysqli_stmt_num_rows($stmt) == 1){
          $email_err = "This email is already taken.";
        } else{
          $email = trim($_POST["email"]);
          // check if e-mail address is well-formed
          if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
          $email_err  = "Invalid email format.";
          }
        }
      } else{
        echo "Oops! Something went wrong. Please try again later.";
      }

      // Close statement
      mysqli_stmt_close($stmt);
    }
  }

  // Validate username
  if(empty(trim($_POST["username"]))){
    $username_err = "Please enter a username.";
  } else{
    // Prepare a select statement
    $sql = "SELECT id FROM users WHERE username = ?";

    if($stmt = mysqli_prepare($link, $sql)){
      // Bind variables to the prepared statement as parameters
      mysqli_stmt_bind_param($stmt, "s", $param_username);

      // Set parameters
      $param_username = trim($_POST["username"]);

      // Attempt to execute the prepared statement
      if(mysqli_stmt_execute($stmt)){
        /* store result */
        mysqli_stmt_store_result($stmt);

        if(mysqli_stmt_num_rows($stmt) == 1){
          $username_err = "This username is already taken.";
        } else{
          $username = trim($_POST["username"]);
        }
      } else{
        echo "Oops! Something went wrong. Please try again later.";
      }

      // Close statement
      mysqli_stmt_close($stmt);
    }
  }

  // Validate password
  if(empty(trim($_POST["password"]))){
    $password_err = "Please enter a password.";
  } else{
    $password = trim($_POST["password"]);
    // Validate password strength
    $uppercase = preg_match('@[A-Z]@', $password);
    $lowercase = preg_match('@[a-z]@', $password);
    $number    = preg_match('@[0-9]@', $password);

    if(!$uppercase || !$lowercase || !$number || strlen($password) < 6) {
      $password_err = "Password should be at least 6 characters in length and should include at least one upper case letter and at least one number.";
    }
  }

  // Validate confirm password
  if(empty(trim($_POST["confirm_password"]))){
    $confirm_password_err = "Please confirm password.";
  } else{
    $confirm_password = trim($_POST["confirm_password"]);
    if(empty($password_err) && ($password != $confirm_password)){
      $confirm_password_err = "Password did not match.";
    }
  }

  // Check input errors before inserting in database
  if(empty($email_err) && empty($username_err) && empty($password_err) && empty($confirm_password_err)){

    // Prepare an insert statement
    $sql = "INSERT INTO users (email ,username, password) VALUES (?, ?, ?)";

    if($stmt = mysqli_prepare($link, $sql)){
      // Bind variables to the prepared statement as parameters
      mysqli_stmt_bind_param($stmt, "sss", $param_email, $param_username, $param_password);

      // Set parameters
      $param_email = $email;
      $param_username = $username;
      $param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash

      // Attempt to execute the prepared statement
      if(mysqli_stmt_execute($stmt)){
        session_start();

        // Store data in session variables
        $_SESSION["loggedin"] = true;
        $_SESSION["id"] = $id;
        $_SESSION["username"] = $username;

        // Redirect user to welcome page
        header("location: index.php");
      } else{
        echo "Something went wrong. Please try again later.";
      }

      // Close statement
      mysqli_stmt_close($stmt);
    }
  }

    // Close connection
    mysqli_close($link);
  }
?>

There's a part of registration.php where I was trying to create a session which will recognize if user is loggedin.

Inserted part of code:

 if(mysqli_stmt_execute($stmt)){
    session_start();

    // Store data in session variables
    $_SESSION["loggedin"] = true;
    $_SESSION["id"] = $id;
    $_SESSION["username"] = $username;

    // Redirect user to welcome page
    header("location: index.php");
  } else{
    echo "Something went wrong. Please try again later.";
  }

I link also login.php:

<?php
// Initialize the session
session_start();

// Check if the user is already logged in, if yes then redirect him to welcome page
if(isset($_SESSION["loggedin"]) && $_SESSION["loggedin"] === true){
    header("location: index.php");
    exit;
}


// Include config file
require_once "config/config.php";

// Define variables and initialize with empty values
$username = $password = "";
$username_err = $password_err = "";

// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){

    // Check if username is empty
    if(empty(trim($_POST["username"]))){
        $username_err = "Please enter username.";
    } else{
        $username = trim($_POST["username"]);
    }

    // Check if password is empty
    if(empty(trim($_POST["password"]))){
        $password_err = "Please enter your password.";
    } else{
        $password = trim($_POST["password"]);
    }

    // Validate credentials
    if(empty($username_err) && empty($password_err)){
        // Prepare a select statement
        $sql = "SELECT id, username, password FROM users WHERE username = ?";

        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "s", $param_username);

            // Set parameters
            $param_username = $username;

            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                // Store result
                mysqli_stmt_store_result($stmt);

                // Check if username exists, if yes then verify password
                if(mysqli_stmt_num_rows($stmt) == 1){
                    // Bind result variables
                    mysqli_stmt_bind_result($stmt, $id, $username, $hashed_password);
                    if(mysqli_stmt_fetch($stmt)){
                        if(password_verify($password, $hashed_password)){
                            // Password is correct, so start a new session
                            session_start();

                            // Store data in session variables
                            $_SESSION["loggedin"] = true;
                            $_SESSION["id"] = $id;
                            $_SESSION["username"] = $username;

                            // Redirect user to welcome page
                            header("location: index.php");
                        } else{
                            // Display an error message if password is not valid
                            $password_err = "The password you entered was not valid.";
                        }
                    }
                } else{
                    // Display an error message if username doesn't exist
                    $username_err = "No account found with that username.";
                }
            } else{
                echo "Oops! Something went wrong. Please try again later.";
            }

            // Close statement
            mysqli_stmt_close($stmt);
        }
    }

    // Close connection
    mysqli_close($link);
}
?>

In my html menu I recognize loggedin users this way:

<?php
  session_start();
  if(isset($_SESSION['loggedin'])){
    $user_logged = 1;
  }else{
    $user_logged = 0;
  }
?>
     

    <div class="sign-in">
      <?php
      if($user_logged==1){ ?>
        <a class="inverted" href="logout.php">Logout</a>
      <?php } else { ?>
        <a class="inverted" href="register.php">Sign in</a>
        <a class="inverted" href="login.php">Login</a>
      <?php } ?>
    </div>
GPA
  • 111
  • 2
  • 10
  • `// Redirect to login page header("location: login.php");` shouldn't this part redirect to home? – Gynteniuxas Sep 20 '20 at 13:10
  • Yes but if I redirect to login page the user is not loggedin and also html menu don't update Sign in and Login it dysplays. @GytisTG – GPA Sep 20 '20 at 13:13
  • you must ALWAYS call the `session_start()` BEFORE you have sent any output at all. So running it after outputting an ` – RiggsFolly Sep 20 '20 at 13:20
  • Yes, but If I 1. Sign up.... 2. Logg in. It shows me that user is loggedin and also the navbar is updated. When I try to put the `session_start()` at the beginning of the code it shows me error. @RiggsFolly – GPA Sep 20 '20 at 13:37
  • Can I store in variable some value from `session_start()` that helps me to output the menu right way? @RiggsFolly – GPA Sep 20 '20 at 13:39
  • In your `menu html` script, move the `session_start()` to the first thing you do in the script. If necessary add `` as the firsy line in the file – RiggsFolly Sep 20 '20 at 13:41
  • Yep I already did it but in registration.php I do not saving into session that user after submitting is loggedin like in login.php file `$_SESSION["loggedin"] = true;` so I think I should add the same code into register.php checkout both files If I'm not wrong. @RiggsFolly – GPA Sep 20 '20 at 13:47
  • This may also be a problem `if(empty($username_err) && empty($password_err)){` – RiggsFolly Sep 20 '20 at 13:49
  • To get errors out of PHP even in a LIVE environment add these 4 lines to the top of any `MYSQLI_` based script you want to debug `ini_set('display_errors', 1); ini_set('log_errors',1); error_reporting(E_ALL); mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);`. This will force any `MYSQLI_` errors to generate an Exception that you can see on the browser as well as normal PHP errors. – RiggsFolly Sep 20 '20 at 13:51
  • `mysqli_stmt_bind_param($stmt, "s", $param_username);` ?? Where did `$param_username` come from ???? – RiggsFolly Sep 20 '20 at 13:52
  • `$_SESSION["loggedin"] = true; $_SESSION["id"] = $id; $_SESSION["username"] = $username; // Redirect user to welcome page header("location: index.php");` I inserted this to registration.php and it solves the problem. Is there any way how to be 100% sure that user is loggedin some sort of command into console or something like that @RiggsFolly – GPA Sep 20 '20 at 14:13
  • I also edited the post so you can check actual code. @RiggsFolly – GPA Sep 20 '20 at 14:25

0 Answers0