Why my PHP script is not allowing successful login?

I am trying to set up a login system to allow a user to access a home page. When I click submit with correct login credentials, the chrome browser just shows the loading signal non-stop and does not reach the desired successful-login home page.

Here is the code for the login page - index.php:

<?php session_start(); if(isset($_POST['submit'])) { //checks if submit is clicked include_once("db.php"); //include db $username = strip_tags($_POST['email']); //get username&password $password = strip_tags($_POST['password']); //removes tags/symbols in string/sql injection // Three different sql injection prevention strategies $username = stripslashes($username); //removes slashes in sql injection $password = stripslashes($password); $username = mysqli_real_escape_string($connection, $username); $password = mysqli_real_escape_string($connection, $password); //ENCRYPTING PASSWORD - in case of db intrusion //$password = md5($password); //----------------------------------------------------------------------------- //Talk to db $sql = "SELECT * FROM users WHERE Email = '$username'"; $qry = mysqli_query($connection, $sql); $row = mysqli_fetch_array($qry); $id = $row['User_ID']; $db_password = $row['Password']; if ($password == $db_password) { $_SESSION['Email'] = $username; $_SESSION['User_ID'] = $id; header("Location: home.php"); } else { header("Location: index.php"); } } ?> JavaScript Example
<div class="container">
    <div class="login">

    <div id="login_form">

        <div class="h1Tag">
            <h1>MyGarden</h1>       
        </div>

        <div class="login_form">
            <form action="index.php" method="post" enctype="multipart/form-data">
                <input type="text" name="email" id="email" placeholder="Email address"><br>
                <input type="password" name="password" id="password" placeholder="Password"><br><br>
                <input type="submit" name="submit" id="submit" value="Log In">
                <p>Not registered?<br><a href="sign_up.php">Sign Up</a></p>
            </form>
        </div>

    </div>

 </div>  
Here is the db.php page: <?php //$connection = new PDO('mysql:host=localhost;dbname=login_credentials;charset=utf8', 'root', ''); $connection = mysqli_connect("localhost", "root", "", "login_credentials"); if (!$connection) { die ("Connection failed: ".mysqli_connect_error()); } ?>

Here is the home age to reach once a successful login is processed - home.php:

<?php session_start(); if(!isset($_SESSION['Email'])) { header("Location: index.php"); } ?> JavaScript Example
<div class="header">

    <div class="top">
        <p>Share your garden with friends from around the world.</p>

        <div class="logout">
            <p><a href="logout.php">Logout</a></p>
        </div>
    </div>

    <div class="bottom">

        <div class="logo">
            <p>MyGarden</p>
        </div>

            <ul class="menu">
                <li><a href="">Home<a/></li>
                <li><a href="">Profile<a/></li>
                <li><a href="">About<a/></li>
                <li><a href="">Settings<a/></li>
                <li><a href="">Privacy<a/></li>
            </ul>
    </div>

    <div class="content">
        <div class="side-menu">
            <ul class="features">
                <li><a href="">Gardners Near Me<a/></li>
                <li><a href="">Country<a/></li>
                <li><a href="">Top Ratings<a/></li>
            </ul>
        </div>
    </div>



</div>

I am using XAMPP to view the application running in Chrome on localhost and have placed all my files in the XAMPP/htdocs folder as convention.

Well, please make sure that if you post here again to place your code inside the tags above when you show us code.
It makes it much easier for us to use and copy.

Now, your code does not look very far off. The main problem is that you keep redirecting to the index page. That is incorrect.
This is the area of your code causing the issues:
[php]
if ($password == $db_password) {
$_SESSION[‘Email’] = $username;
$_SESSION[‘User_ID’] = $id;
header(“Location: home.php”);
} else {
header(“Location: index.php”);
}
[/php]
As you see, if it works, it sets up the session info and moves onto the home.php page. BUT, if it fails, it re-runs ITSELF constantly. Never ending. Remember, that this code is already on the index.php code. No need to loop forever there. Also, you have no way of telling the user that his login failed. Normally, you would set an error variable like $error_message=“xyz” and then show that error in your HTML section of the page. At the very least, you should just display the error. (This will not show up correctly in the page, though!) So, this would be a better version of it:
[php]
if ($password == $db_password) {
$_SESSION[‘Email’] = $username;
$_SESSION[‘User_ID’] = $id;
header(“Location: home.php”);
} else {
$error_message = “Authentication failed for this email and password!”;
}
[/php]
Then, further down in your HTML section, you would display that error message using:
[php]
<?PHP echo "

" . $error_message . "
"; ?>
[/php]
You would place this just above the form display so the user can see their error. Also, you might want to go a step further and first check for the email address and if not in the database, say so and then check for the password to see if it does not match and say that. This would give the user better information about what is wrong.

Hope this helps!

Thank you for replying ErnieAlex. I didn’t realise I was causing a loop when there was an incorrect password.

I have done what you suggested, but when running the page on xampp, the page is ever-loading non-stop.

I was getting errors with this PHP error message on the style attribute color:

MyGarden
[php]<?php echo "
" . $error_message . "
"; ?>[/php]

So I moved it here:

[php]<?php echo "

" . $error_message . "
"; ?>[/php]



Not registered?
Sign Up

So sorry, Naz, my flying fingers miss-typed it…

Try:
[php]
<?php echo "

" . $error_message . "
"; ?>
[/php]
Note: You can not nest double-quotes or single-quotes, you must alternate them. PHP can echo like echo “something”, and
it can echo like echo "something ‘great’ " but, not echo "something “great” " … Make sense? Hope so. And, sorry…

No worries haha! :slight_smile:

I have done what you suggested, and when running the page on chrome, the page is ever-loading non-stop. It doesn’t reach the index page, but shows a blank page with the error message: “This site can’t be reached.”.

Well, I don’t see that message anywhere in your code. Therefore, I will guess you miss-spelled one of your page names.

So, when you get that message, look at the URL address line and see which page it is not loading. My guess is that it is
some sort of spelling issue. Home.php is NOT home.php… In PHP caps are very important!

There is a simple way while testing the “flow” of a test page. Just use the DIE() function. For example, you can just add it to
the login page to see what is being handled. You could add this for the login-check code to view what is happening:
[php]
if ($password == $db_password) {
$_SESSION[‘Email’] = $username;
$_SESSION[‘User_ID’] = $id;
echo "password: " . $password . “
”;
echo "$database password: " . $db_password . “
”;
echo "username: " . $username . “
”;
echo "id: " . $id . “
”;
echo "SESSION-email: " . $_SESSION[‘email’] . “
”;
echo "SESSION-ID: " . $_SESSION[‘User_ID’] . “
”;
die(“DONE!”);
header(“Location: home.php”);
} else {
header(“Location: index.php”);
}
[/php]
You can comment them out or delete them after you are sure the code is correct. Run the page and it will stop at the DIE()
function point. Then, review the data and verify that you are creating the correct values. If they are correct, you can look at the
home.php page and do something similar to see if the session variables are getting to it. Does that make sense?

Hope all this helps…

If I remove session_start() from index.php, the page will load with the error:

Notice: Undefined variable: error_message in C:\xampp\htdocs\MyProj\index.php on line 58

Line 58 is where the $error_message is supposed to be printed:

[php]<?php echo "

" . $error_message . "
"; ?>[/php]

I have predefined $error_message as an empty string.

Don’t know if this will be useful.

Predefine it as a null string
[php]$error_message = NULL;[/php]
(which I believe is also a total empty string “”) and then do the following:

[php]<?php echo ($error_message) ? '

' . $error_message . '
' : NULL; ?>[/php]

I have done what was suggested, but what happens is the index page fails to load and when testing with just echoing “success” for logging in or “failed” for not successfully logging in, it does not work. I can’t seem to find the error anywhere. If I remove session_start(), I can see the index page, otherwise it fails to load.

[php]<?php
session_start();
include_once(“db.php”); //include db

if(isset($_POST['submit'])) { 							//checks if submit is clicked

	$username = strip_tags($_POST['email']); 			//get username&password
	$password = strip_tags($_POST['password']); 		//removes tags/symbols in string/sql injection

	// Three different sql injection prevention strategies
	$username = stripslashes($username); //removes slashes in sql injection
	$password = stripslashes($password);
	
	$username = mysqli_real_escape_string($connection, $username); 
	$password = mysqli_real_escape_string($connection, $password);

	//ENCRYPTING PASSWORD - in case of db intrusion
	//$password = md5($password);
	//-----------------------------------------------------------------------------
	//Talk to db
	$sql = "SELECT * FROM users WHERE Email = '$username' LIMIT 1";
	$qry = mysqli_query($connection, $sql);
	
	$row = mysqli_fetch_row($qry);
	$id = $row['User_ID'];
	$db_password = $row['Password'];
	
	$error_message = NULL;
	 
	if ($password == $db_password) {
		$_SESSION['Email'] = $username; 
		$_SESSION['User_ID'] = $id;
		$error_message = "status";
		header("Location: home.php");
	} else {
		//$error_message = "Incorrect password.";
		echo "failed";
	}
	
}

?>[/php]

JavaScript Example
<div class="container">
	<div class="login">

	<div id="login_form">
		
		<div class="h1Tag">
			<h1>MyGarden</h1>		
		</div>
		<div class="login_form">
			<form action="index.php" method="POST" >
				<input type="text" name="email" id="email" placeholder="Email address"><br>
				<input type="password" name="password" id="password" placeholder="Password"><br><br>
				<input type="submit" name="submit" id="submit" value="Log In">
				<p>Not registered?<br><a href="sign_up.php">Sign Up</a></p>
			</form>
		</div>
	
	</div>

 </div>  

[php]<?php

$connection = mysqli_connect(“localhost”, “root”, “”, “login_credentials”);

if (!$connection) {
die ("Connection failed: ".mysqli_connect_error());
}

?>[/php]

Okay, let’s think of the logic of the site.

If someone goes to the index page, they are starting from scratch. If they enter items that fail, they are starting from scratch. Therefore, you don’t care if they have attempted to log in yet. You are just starting over. So, I would make the code set the session info to nulls first. Then, check for inputs and if the validation passes, then set the session values. What is good about this is that it makes sure you do not leave session variables with data inside them. Not a big thing as the session is gone once the browser is closed, but, it makes sure they can’t type another page in your site and get pass the check for a session variable NOT being empty… I have seen where an index page leaves data inside a session variable that contains data in place and then you manually change pages to another “home” type of page and the data is there so checking for an empty value fails and lets the user into all the rest of the pages. Seldom do programmers recheck values on each following pages.

Just my two cents…

Sponsor our Newsletter | Privacy Policy | Terms of Service