Jump to content

PHP sign in user after registration


FocuZst

Recommended Posts

I'm creating a simple login and registration form. What I'm trying to do is when a user registers, it should log them in. In order to get logged in, the user's ID that gets registered needs to be sent to the home page so the username can be displayed. I'm not sure what is wrong with my code.

 

Register:

<!DOCTYPE html><?php    session_start();    if(isset($_SESSION['userID']) AND !empty($_SESSION['userID'])) {        header("Location: home.php");    }    if(isset($_POST['register'])) {        $firstName = mysqli_real_escape_string($dbConnect, $_POST['firstName']);        $lastName = mysqli_real_escape_string($dbConnect, $_POST['lastName']);        $username = mysqli_real_escape_string($dbConnect, $_POST['username']);        $email = mysqli_real_escape_string($dbConnect, $_POST['email']);        $password = mysqli_real_escape_string($dbConnect, $_POST['password']);{           // Check if data exists already in the database            $exists = mysqli_query($dbConnect, "SELECT user_id, username, email FROM users WHERE username = '$username' AND email = '$email'");            $row = mysqli_fetch_array($exists);        $dbusername = $row['username'];        $dbemail = $row['email'];        if ($username == $dbusername) {            die("Username already taken.");        }   else if ($email == $dbemail) {            die("Email already registered.");        }}        $registerUser = "INSERT INTO users (first_name, last_name, username, email, password) VALUES('$firstName', '$lastName', '$username', '$email', '$password')";{           // Select ID from registered user        $selectID = "SELECT user_id FROM users WHERE username = '$username'";        $selectID_Query = mysqli_query($dbConnect, $selectID);        $fetch = mysqli_fetch_array($selectID_Query);        $userID = $fetch['user_id'];        $_SESSION['userID'] = $userID;}        if(mysqli_query($dbConnect, $registerUser)) {            header("Location: home.php");        }   else {            echo "<script>alert('error while registering you...');</script>";        }    }    include "includes/head.php";    include "includes/nav.php";?>    <div id="main-content">        <div class="welcome-msg">            <h1 class="huge">Registration form</h1>            <h3 class="medium">Please fill in all the inputs</h3>            <form id="login-form" method="post">                <label for="firstName">First Name</label>                <input type="text" name="firstName" id="firstName" required>                <label for="lastName">Last Name</label>                <input type="text" name="lastName" id="lastName" required>                <label for="username">Username</label>                <input type="text" name="username" id="username" required>                <label for="email">Email</label>                <input type="email" name="email" id="email" required>                <label for="password">Password</label>                <input type="password" name="password" id="password" required>                <button type="submit" name="register">Register</button>            </form>        </div>    </div></body>

Home:

<!DOCTYPE html><html><?phpsession_start();if(!isset($_SESSION['userID'])) {    header("Location: index.php");}$tUsers_Select_Query = mysqli_query($dbConnect, "SELECT * FROM users WHERE user_id=".$_SESSION['userID']);$row = mysqli_fetch_array($tUsers_Select_Query);include "includes/head.php";include "includes/nav.php";?>    <div id="main-content">        <h1 class="huge">Welcome back, <?php echo $row['username'] ?>!</h1>        <a href="/lr/logout.php?logout">Logout</a>    </div></body>

If you need any more details, please comment.

Link to comment
Share on other sites

First, you need to call session_start() before any HTML tags (or even whitespace) is printed out.

<!DOCTYPE html><?php    session_start();

...needs to look like...

<?php    session_start();// ... other code here ...?><!DOCTYPE html>

Very important: You're storing your password in plaintext. Don't do that. See password_hash() and password_verify().

 

I see that you're using mysqli_real_escape_string(). This is a mistake. The proper way to prevent SQL injection is to use prepared statements, not to escape input.

 

Reference: https://secure.php.net/manual/en/mysqli.prepare.php

Edited by sarciszewski
Link to comment
Share on other sites

You're not doing any error checking either, you're assuming that your queries are returning data when they might not be. Add this to the top of your code while you're debugging:

ini_set('display_errors', 1);error_reporting(E_ALL);
The major problem I see with your logic is that you try to select the new ID before you insert the record, and showing all error messages would help point that out (since you're assuming that query is returning a record). Instead of selecting a record after insert, you can use this:http://php.net/manual/en/mysqli.insert-id.php
  • Like 1
Link to comment
Share on other sites

First, you need to call session_start() before any HTML tags (or even whitespace) is printed out.

<!DOCTYPE html><?php    session_start();

...needs to look like...

<?php    session_start();// ... other code here ...?><!DOCTYPE html>

Very important: You're storing your password in plaintext. Don't do that. See password_hash() and password_verify().

 

I see that you're using mysqli_real_escape_string(). This is a mistake. The proper way to prevent SQL injection is to use prepared statements, not to escape input.

 

Reference: https://secure.php.net/manual/en/mysqli.prepare.php

 

I haven't learned about SQL injections yet. That's why I'm not worried about security now. This login and registration system is just for learning purposes.

Link to comment
Share on other sites

You're not doing any error checking either, you're assuming that your queries are returning data when they might not be. Add this to the top of your code while you're debugging:

ini_set('display_errors', 1);error_reporting(E_ALL);
The major problem I see with your logic is that you try to select the new ID before you insert the record, and showing all error messages would help point that out (since you're assuming that query is returning a record). Instead of selecting a record after insert, you can use this:http://php.net/manual/en/mysqli.insert-id.php

 

 

Thanks man! All I had to do was

if(mysqli_query($dbConnect, $registerUser)) {	$_SESSION['userID'] = mysqli_insert_id($dbConnect); // <<-- Add this	header("Location: home.php");	}	else {		echo "<script>alert('error while registering you...');</script>";}
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...