Login form not working

am new in php am trying make a login form for my user when ever i login, login page keep on redirecting me back to login form. any help here please…

this is my code

<?php error_reporting(E_ALL); ini_set('display_errors', 1); session_start(); $host = "127.0.0.1"; $user = "root"; $pass = ""; $db = "xperia"; $connect = mysqli_connect($host, $user, $pass, $db); $data_base = mysqli_select_db($db, $connect); if (isset($_POST['submit'])) { $username = stripslashes($_POST['username']); $password = stripslashes($_POST['password']); $username = mysqli_real_escape_string($_POST['username']); $password = mysqli_real_escape_string($_POST['password']); $sql = "SELECT * FROM xperia WHERE username='".$username."' AND password='".$password."' LIMIT 1"; $res = mysqli_query($connect, $sql) or die (mysql_error($connect)); if (mysqli_num_rows($res) == 1) { $_SESSION['username'] = $username; header("Location: welcome.php"); exit(); } else { echo "$username Invalid login information. Please return to the previous page."; exit(); } } ?>

Set sessions to the top of your page. You have to also check whether they are logged in or not. Basically, if they aren’t, redirect them back to the login page. If they are logged in, redirect them back to a desired page. Also, I would like to suggest to check the login page for the session username as well. This is so if they are logged in, they don’t need to login anymore and redirect them back to the desired page.

Also, don’t check for isset($_POST[‘submit’[). Read both these 2 articles in full before you do anything. They are both very helpful.

http://stackoverflow.com/questions/10943060/isset-postsubmit-vs-serverrequest-method-post
http://stackoverflow.com/a/29255185

i read the article it was cool thanks for the link but that does not answer my question "whenever i click “login” submit button it redirect me back to my login form " am clear sure my database is clean

Can you show us the code for the login form? I see nothing in there that would redirect to the login form, or do you mean that it displays the message for the user to go back there?

I did tell you. I told you to basically set up a logic where you check for sessions first then check if the session username was set. If not, prompt them a login page. Apply that logic to your code and if you get any errors. You can report it back here.

this is the code full code

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

error_reporting(E_ALL);
ini_set('display_errors', 1);

$host = "127.0.0.1";
$user = "root";
$pass = "";
$db = "xperia";

$connect = mysqli_connect($host, $user, $pass, $db);
$data_base = mysqli_select_db( $connect, 'xperia');

if (isset($_POST['submit'])) {
    
    $username = stripslashes($_POST['username']);
    $password = stripslashes($_POST['password']);
    $username = mysqli_real_escape_string($connect, $_POST['username']);
    $password = mysqli_real_escape_string($connect, $_POST['password']);
    
    $sql = "SELECT * FROM xperia WHERE username='".$username."' AND password='".$password."' LIMIT 1";
    $res = mysqli_query($connect, $sql) or die (mysql_error($connect));
    
    if (mysqli_num_rows($res) == 1) {
        $_SESSION['username'] = $username;
        header("Location: welcome.php");
    exit();
} else {
    echo '<script type="text/javascript">alert("Username and password incorrect!");     window.location="login.php";</script>';

    exit();
}
}

?>
<html>
<form action = "login.php" method = "POST" >
<tr>
<td><input type = "text" name = "username" /></td>
</tr>

<tr>
<td><input type = "password" name = "password" /></td>
</tr>
     <input type="submit" name="submit"  value="Submit"/>

</form>
</html>

I’ll rewrite those codes when I come back from work in 8 hours. Your code is really messy and is prone to SQL Injection.

That aside, how is your password stored in the database? In plain text? If it’s not stored in plain text, I can’t see where you encode what the user typed before the query. Have you tried echoing the vars after you’ve escaped them, then run the query directly into the MySQL admin with those values?

With that code, the <!DOCTYPE HTML> line will be output and you will get a “headers already sent” error. i.e. The SESSION will not work.

1 Like

i removed !DOCTYPE HTML it still giving me the same thing

@spaceshiptrooper still watin for the code?

Try now, even your code looks…

    <?php
session_start();

error_reporting(E_ALL);
ini_set('display_errors', 1);

// refactor
$host = "127.0.0.1";
$user = "root";
$pass = "";
$db = "xperia";

//refactor
$connect = mysqli_connect($host, $user, $pass, $db);
$data_base = mysqli_select_db( $connect, 'xperia');

// if you have a single form on the page, use this method
if ($_SERVER['REQUEST_METHOD'] == 'POST') { 
    // grab the posted data
    $username = htmlspecialchars($_POST['username']));
    $password = $_POST['password'];

   // some validation rules here
    

    // refactor
    $sql = "SELECT * FROM xperia WHERE username='".$username."' AND password='".$password."' LIMIT 1";
    $res = mysqli_query($connect, $sql) or die (mysql_error($connect));
    
    if (mysqli_num_rows($res) === 1) {
        $_SESSION['username'] = $username;
        header("Location: welcome.php");
        exit();
    } else {
        $status =  '<script type="text/javascript">alert("Username and password incorrect!");window.location="login.php";</script>';
    }
}

?>

<!DOCTYPE HTML>
<html>
<head></head>
<body>
<form action="login.php" method="POST" >
<tr>
<td><input type="text" name="username" /></td>
</tr>

<tr>
<td><input type ="password" name="password" /></td>
</tr>
     <input type="submit" value="Submit"/>
<?php 
if (isset($stauts)) {
    echo $status;
}
?>
</body>
</form>
</html>

With that code, the whitespace before the PHP start will be output and you will get a “headers already sent” error. i.e. The SESSION will not work.

To use cookie-based sessions, session_start() must be called before outputing anything to the browser.

Ok, so you’re basically going to have to actually change your code base because the codes that I am about to post uses up-to-date codes.

What it uses

  • password_verify
  • Checks to see if both session and cookie are the same. (Adopted from Facebook). ← I’ve personally tested this on Facebook and it works. It basically checks to see if the cookie is modified. If it has been modified, the user gets logged off right away. This is to prevent users from logging into someone else’s account by exploiting the cookies.

db.php

<?php
/*

        In this part, you check whether the PHP version is between 5.2 and 5.4.

*/

if((PHP_VERSION > '5.2' && PHP_VERSION < '5.4')) {

    // Since your PHP version is between 5.2 and 5.4, you can use session_id() to check if sessions already have been started.
    if(session_id() == '') {

        session_start(); // Start the session since the session hasn't been started

    }

} elseif((PHP_VERSION >= '5.4')) {

    // Since your PHP version is 5.4 and above, you can use session_status as it is only available for 5.4 and higher.
    if(session_status() == PHP_SESSION_NONE) {

        session_start(); // Start the session since the session hasn't been started

    }

}

/*

        End the top notice here

*/

// Use mysqli_report to report where exactly has the code gone wrong whether it'd be a typo trying to find a user
// Or maybe even a non-existing table.
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

$host = "127.0.0.1";
$user = "root";
$pass = "root";
$db = "xperia";

try {

    $connection = new mysqli($host, $user, $pass, $db); // Your connection is good

} catch(mysqli_sql_exception $e) {

    throw $e; // Basically print the error

}

if(file_exists('password_hash.php')) {

    require('password_hash.php'); // require the alternative PHP password_hash file.

} else {

    print('You are missing the password_hash.php file. <a href="https://github.com/ircmaxell/password_compat/tree/master/lib" target="_new">Click here</a> to download it. Rename the file password.php to password_hash.php.');
    die();

}

index.php

<?php
require('db.php');

// Check to see if the session userid exists.
if(!isset($_SESSION['userid'])) {

        header('Location: login.php'); // Since the session userid doesn't exist, redirect them back to the login page.
        die(); // Ignore anything after this. Redundant, but trying to be safe here.

} else {

    // Check to see if the cookie some_cookie_thing exists
    if(isset($_COOKIE['some_cookie_thing'])) {

        // If it exists, that's good.

        // Check to see if the session userid and some_cookie_thing are equaled.
        if($_SESSION['userid'] == $_COOKIE['some_cookie_thing']) {

            // If you some how reach to this point, that means that the session userid exists
            // And the cookie some_cookie_thing has not been modified yet.

            $id = filter_var($_SESSION['userid'], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH); // Append the session userid a variable.

            $mysqli = $connection->prepare("SELECT id, username, password FROM xperia WHERE id = ?"); // SQL query string
            $mysqli->bind_param('i', $id); // Bind the userid to avoid SQL Injections.
            $mysqli->execute(); // Execute the query
            $mysqli->store_result(); // Store the result for later checking

            if($mysqli->num_rows) {

                $mysqli->bind_result($id, $username, $password);  // Bind and append variables to the columns

                // Make a while loop to fetch the data
                while($mysqli->fetch()) {
?>
<!DOCTYPE HTML>
<html>
<p><?php print($username); ?></p>
</html>
<?php
                }

            } else {

                // Since the query line didn't return anything.
                // Unset the session userid and redirect the user back to the login page.
                // Unset the session userid and cookie some_cookie_thing if they exit.

                if(isset($_SESSION['userid'])) {

                    unset($_SESSION['userid']);

                }

                if(isset($_COOKIE['some_cookie_thing'])) {

                    setcookie('some_cookie_thing', '', time() - 3600, '/', $_SERVER['SERVER_NAME'], isset($_SERVER['HTTPS']), true);

                }

                header('Location: login.php');
                die();

            }

        } else {

            // Since the session userid and the cookie some_cookie_thing didn't equal to each other,
            // Most likely the user has used a 3rd party program to modify their cookies.
            // Unset the session userid and cookie some_cookie_thing if they exit.

            if(isset($_SESSION['userid'])) {

                unset($_SESSION['userid']);

            }

            if(isset($_COOKIE['some_cookie_thing'])) {

                setcookie('some_cookie_thing', '', time() - 3600, '/', $_SERVER['SERVER_NAME'], isset($_SERVER['HTTPS']), true);

            }

            header('Location: login.php');
            die();

        }

    } else {

        // Since the session userid doesn't exist
        // Unset the session userid and cookie some_cookie_thing if they exit
        // And redirect the user to the login page.

        if(isset($_SESSION['userid'])) {

            unset($_SESSION['userid']);

        }

        if(isset($_COOKIE['some_cookie_thing'])) {

            setcookie('some_cookie_thing', '', time() - 3600, '/', $_SERVER['SERVER_NAME'], isset($_SERVER['HTTPS']), true);

        }

        header('Location: login.php');
        die();

    }

}

login.php

<?php
require('db.php'); // Require the DB file

// Check to see if session userid exists first
if(isset($_SESSION['userid'])) {

    header('Location: index.php'); // Since the session userid exists, redirect them back to the index page.
    die(); // Ignore anything after this. Redundant, but trying to be safe here.

} else {

    // As said in my original post, using isset($_POST['submit']) is an amateur move
    // And will fail when the user hits the "Enter" key on their keyboard on a random text box.
    if($_SERVER['REQUEST_METHOD'] == 'POST') {

        if($_POST['username'] == '') {

            // Check to see if the username field is empty
            // If so, give them the first error.

            $_SESSION['error'] = 1; // Username was not typed in.
            header('Location: login.php'); // Redirect them back to the login page.
            die(); // Ignore anything after this. Redundant, but trying to be safe here.

        } elseif($_POST['password'] == '') {

            // Check to see if the password field is empty
            // If so, give them the second error.

            $_SESSION['error'] = 2; // Password was not typed in.

            // However check to see if the username was typed in
            if($_POST['username'] != '') {
                $_SESSION['usename'] = $_POST['username']; // If so, set the session usename to the posted username
            }

            header('Location: login.php'); // Redirect them back to the login page.
            die(); // Ignore anything after this. Redundant, but trying to be safe here.

        } else {

            $username = filter_var($_POST['username'], FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH); // FIlter the username so no bad characters are in here.
            $username = trim($username); // Trim the username so that there aren't any spaces in the username
            $password = $_POST['password']; // Don't EVER EVER EVER EVER modify or touch the user's input password whether you "think" it's safe or not.

            $mysqli = $connection->prepare("SELECT id, username, password FROM xperia WHERE username = ?"); // Your query string
            $mysqli->bind_param('s', $username); // Bind the posted username to the query string to avoid SQL Injection.
            $mysqli->execute(); // Execute the query line
            $mysqli->store_result(); // Store the result for later checking

            // Check to see if the query line returns a 
            if($mysqli->num_rows) {

                $mysqli->bind_result($id, $username, $get_password); // Bind and append variables to the columns

                // Make a while loop to fetch the data
                while($mysqli->fetch()) {

                    // Use PHP's default password_verify to verify whether the passwords match or not
                    if(password_verify($password, $get_password)) {

                        setcookie('some_cookie_thing', $id, 0, '/', $_SERVER['SERVER_NAME'], isset($_SERVER['HTTPS']), true); // a cookie on the current domain
                        $_SESSION['userid'] = $id; // Set the session userid as the ID of the current user.
                        header('Location: index.php'); // Redirect them back to the index page.
                        die(); // Ignore anything after this. Redundant, but trying to be safe here.

                    } else {

                        $_SESSION['error'] = 3; // The account exists, but the password was typed in wrong.
                        $_SESSION['usename'] = $_POST['username']; // Set 
                        header('Location: login.php'); // Redirect them back to the login page.
                        die(); // Ignore anything after this. Redundant, but trying to be safe here.

                    }

                }

            } else {

                $_SESSION['error'] = 4; // The account really doesn't exist in the database.
                header('Location: login.php'); // Redirect them back to the login page.
                die(); // Ignore anything after this. Redundant, but trying to be safe here.

            }

        }

    }
?>
<!DOCTYPE HTML>
<html>
<?php
// Show a customized error to the user.
if(isset($_SESSION['error'])) {

    if($_SESSION['error'] == 1) {
?>
<p>Username not typed in.</p>
<?php
    } elseif($_SESSION['error'] == 2) {
?>
<p>Password not typed in.</p>
<?php
    } elseif($_SESSION['error'] == 3) {
?>
<p>Your username or password is not correct.</p>
<?php
    } elseif($_SESSION['error'] == 4) {
?>
<p>Your account does not exist.</p>
<?php
    }

}
?>
<form action = "login.php" method = "POST" >
<tr>
<td><input type = "text" name = "username" value = "<?php if(isset($_SESSION['usename'])) { print($_SESSION['usename']); } ?>" /></td>
</tr>

<tr>
<td><input type = "password" name = "password" value = "" /></td>
</tr>
<input type="submit" name="submit"  value="Submit"/>
</form>
</html>
<?php
    if(isset($_SESSION['error'])) {

        // If session error exists, unset it so when the user comes back to the same page and does something different.
        // They will be prompt a new error instead of the same error.
        unset($_SESSION['error']);

    }

    if(isset($_SESSION['usename'])) {

        // If session usename exists, unset it since it is a temporary session.
        // They will be prompt a new username if they mess up again with a new username.
        unset($_SESSION['usename']);

    }

}

NOTE:

Please take note that these logic are bad because we are nesting HTML codes within PHP codes. It is ideal to save the HTML part in a separate file and require it from the PHP files. Also, you don’t have to use these codes if you don’t want to. I won’t be forcing you to.


If you find an error some where, let me know.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.