Jump to content

login function works, but (if condition isset) not letting me see the page


RaiN3772

Recommended Posts

Hello there, totally new to php and been learning it in few weeks, and im in love with its potential.

so im here to get some help creating a login function.

 

what im getting is "Please fill both the username and password fields" which the code is "exit ("Please fill both the username and password fields");"

what im supposed to get is a normal html form to submit the username and password

here is the html code

<?php
include 'inc/function_login.php';
?>
<html>
	<head>
		<meta charset="utf-8">
		<title>Login</title>
	</head>
	<body>
		<div class="login">
			<h1>Login</h1>
			<form action="index.php" method="post">
				<input type="text" name="username" placeholder="Username" id="username" required>
				<input type="password" name="password" placeholder="Password" id="password" required>
				<input type="submit" value="Login">
			</form>
		</div>
	</body>
</html>

 

and here is the php code (i know you dont wanna read 100k lines of codes that will probably gonna give you a headache but im helpless at this point, so thanks)

<?php

// Initialize the session
session_start();

// Include Database Configuration File
require_once "db_config.php";

// Include Langauge File
require_once "language.php";

// Attempt to connect to the database server

$con = mysqli_connect($db_host, $db_username, $db_password, $db_name);
if ( mysqli_connect_errno() ) {
	// If there is an error with the connection, stop the script and display the error.
	exit('Failed to connect to MySQL: ' . mysqli_connect_error());
}

// Check if the data from the login form was submitted, isset() will check if the data exists.
if ( !isset($_POST['username'], $_POST['password']) ) {
	// Could not get the data that should have been sent.
	exit ("Please fill both the username and password fields");
}

// Prepare our SQL, preparing the SQL statement will prevent SQL injection.
if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
	// Bind parameters (s = string, i = int, b = blob, etc), in our case the username is a string so we use "s"
	$stmt->bind_param('s', $_POST['username']);
	$stmt->execute();
	// Store the result so we can check if the account exists in the database
	$stmt->store_result();

    if ($stmt->num_rows > 0) {
        $stmt->bind_result($id, $password);
        $stmt->fetch();
        // Account exists cool, Please verify the password.
        if (password_verify($_POST['password'], $password)) {
            // Verification success! User has logged-in!
            // Create sessions, so we know the user is logged in
            session_regenerate_id();
            $_SESSION['loggedin'] = TRUE;
            $_SESSION['name'] = $_POST['username'];
            $_SESSION['id'] = $id;
            header('Location: home.php');
        } else {
            // Incorrect password
            echo 'Incorrect username and/or password!';
        }
    } else {
        // Incorrect username
        echo 'Incorrect username and/or password!';
    }


	$stmt->close();
}
?>

 

i would be glad if someone point me to the right way, or at least tell me what is totally wrong

Link to comment
Share on other sites

From your first post I am guessing that you are seeing the form.  Are you then asking why you don't see that form again when there is a failure? 

You need to modify your processing code to start with PHP only and see if you have received any inputs from a POST.  If not, THEN send out the html and exit.  Once you do receive the POST input from that form, process it with PHP only and decide what happens next.  If you have a user problem, send out the form again along with a message and exit.  If no problem, then send the script to the next script to begin using the app.  Do Not Mix up the php code with the HTML code.  Makes for a terrible time to do maintenance down the road and to simple read thru the script.  Structure your scripts to do the startup things first, then to check what inputs you have or don't have and then do the processing and finally send out the html.  Structure is key.

Proper html structure would suggest using the label tag to preface all of your input tags.

If you are just beginning, I and many others here would advise that you stop and read up on using PDO instead of mysqlI.  Much easier to grasp, to use and to work with than mysqli.

Link to comment
Share on other sites

You have shown us your html for the login and php code which processes the login.

Your code references three php file

  • login.php
  • home.php
  • index.php

What we don't know is where the code you have shown us is placed.

Nor do we know what exactly which you are running when you see the error. We do not know the flow that is taking place from one to the next, and given your problem, I'm not sure you do either.

Typical flow is like this, but it looks like you are starting at "X"

image.png.eb32c442800743ca9f097bfc22c83b05.png

Link to comment
Share on other sites

i gave up...

 

im not sure what exactly is the problem. it was working fine without any error till i organized the files, all i did created a new folder called inc, then created a file called db_config.php which is the normal mysql connection (nothing feaky lol)

<?php

// Database configuration
$db_host = 'localhost';
$db_username = 'root';
$db_password = '';
$db_name = 'somename';

?>

then i included the file function_login.php in index.php (which is the login page) and changed the form action from function_login.php to index.php nothing fancy you know.

 

but what i think is going on here that the functions is working before i submitting the form (which it was working perfectly before i organized the files)

Link to comment
Share on other sites

Let's start over.  Ok - you are not configuring your db in this script.  Your db server and you have done that already and that's it.  Or your host provider has given you the screen to do that config and setup your db and create your tables.  So - the only 'db' thing in your scripts from now on is to make a connection.  Call that 'db_connect' to avoid confusion.  And add a dbname to that function so that you can call it with the desired name and make the connection flexible.

Now your script should begin with a session_start call.  Then you should have a couple lines to enable error checking so that during your development your script can let you know what is wrong

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

Put that into a small script and store it.  Then require it in all of your scripts.  What I do is add a line to check for that status of a '$in_devl' variable so that once I'm done developing I set that var to false, otherwise it is true so that the error checking can be on/off as needed very easily.

Now as Barand showed you, check if you received a post which means you should have inputs to look for and process.  If no post, then send out your login form and exit(as I said earlier).  So why don't you start with just this part and see how far you get?  Personally I use a php function to do the html send so that I can easily get it done from anywhere in my script which saves you from having to figure out where to put it.  Add some global vars to it so that you can pass your received inputs back to the form when you have errors and want to re-show them.   

Can do?  Having fun?  Just do the 2 things I recommended and work on just starting up, not finding any post, and sending out the form by calling your 'DisplayPage()' function (tha'ts what I call it). 

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.