Login Application

Hey Guys,

I am creating a login application using PHP/Phpmyadmin and I am having an issue. I found another program online and I am mimicking its function, but I am unable to get it to work. Basically I have a database named ‘vendors’ with a table called ‘users’. I want the login app to pull the username and password from my database and approve/reject depending on if the user is found. I have been working on this for some time and have not been able to figure it out. Any help is much appreciated.

<?php session_start(); ?>
<?php include('dbcon.php'); ?>
<html>
<head>
<title>LOGIN PAGE</title>
<link rel="stylesheet" type="text/css" href="style2.css">
<link rel="shortcut icon" href="img/favicon.ico" type="image/x-icon">
</head>
<body>
<div class="form-wrapper">
  
  <form action="#" method="post" autocomplete="off">
    <h3>Login here</h3>
	
    <div class="form-item">
		<input type="text" name="username" required="required" placeholder="Username" autofocus required></input>
    </div>
    
    <div class="form-item">
		<input type="password" name="password" required="required" placeholder="Password" required></input>
    </div>
    
    <div class="button-panel">
		<input type="submit" class="button" title="Log In" name="login" value="Login"></input>
    </div>
  </form>
  <?php
	if (isset($_POST['login']))
		{
			$username = mysqli_real_escape_string($con, $_POST['user']);
			$password = mysqli_real_escape_string($con, $_POST['pass']);
			
			$query 		= mysqli_query($con, "SELECT * FROM users WHERE  password ='$password' and username ='$username'");
			$row		= mysqli_fetch_array($query);
			$num_row 	= mysqli_num_rows($query);
			
			if ($num_row > 0) 
				{			
					$_SESSION['id']=$row['id'];
					header('location:home.php');
					
				}
			else
				{
					echo 'Invalid Username and Password Combination';
				}
		}
  ?>
  <div class="reminder"><br><br>
    <p>Not a vendor? <a href="register.php">Register Here</a></p>
    
  </div>
  
</div>

</body>
</html>

pdo is a better, safer method of working with a database. pdo is very easy to understand. i made a login using pdo in two hours. I spent over an hour reading about pdo.
https://phpdelusions.net/pdo

i think that you need a placeholder for variables. i never learned mysql until last month so i could be wrong. For sure: you need an exit or die() immediately following a header redirect.

pdo:

$query = 'SELECT username, password FROM members WHERE username = :PostUser';
$stmt = $dbh->prepare($query);
$stmt->execute(array(':PostUser' => $username));
$result = $dbh->fetch();
$myAppUser = htmlentities($result['username'], ENT_QUOTES, "UTF-8");
$myAppUserPass = $result['password'];

compare the values pulled from the db with the values posted for authentication. Then, set the session variable. Way i see it: htmlentities out and for input comparison with out, so you don’t forget to escape the dangers of the unknown.

1 Like

For complete beginners something like Idiorm or Paris is even easier (and they use PDO internally).

1 Like

I like the thought of using an ORM, but I think understanding of the database is an important aspect, even more so as a beginner. I worked for a company, that even the senior developers had no clue how a database functioned (You know how bad it is when you start saying that a stored procedure would be more beneficial for an issue and the entire room has puzzled looks on their faces?) because of always using ORMs, and in PHP it isn’t that typical, .NET it is far more common to see the disconnect and python developers also fail in this respect.

1 Like

I have never used PDO before, but looking at the link you gave me it does make some sense. I myself am a newb to coding these programs, but I appreciate the link and suggestions.

1 Like

i have a working login but i am still learning too. However, if you get stuck using pdo, then please ask for help. I can post my login code if it will help you. Alot of members are expert level coders, so they can monitor this post and make necessary suggestions/changes. We are a community and helping each other is very important.

2 Likes

For the most immediate problem as to why your code is not working, see the items in this recent thread - Help needed-mysql-php

You have a problem that setting php’s error related settings will help you find.

I appreciate that John if you can post your login code. I am not sure how to integrate it with what I have. I can understand the functionality of most of the elements, but I have a long way to go to fully learn coding.

1 Like

i have a form with two input text fields name=“username” and name=“password” respectively.
I also set sha3-512 csfr token in a hidden input name=“visitorToken”, then i use an if hash_equals comparing the token with a session variable.

login.php stored outside the web root but accessed via include

if (hash_equals($_SESSION['matchToken'], $_POST['visitorToken'])) {
  $_SESSION['matchToken'] = null;
} else {
  header("Location: ../");
  exit;
}

$username = trim(htmlentities($_POST['username']), ENT_QUOTES, "UTF-8");
$password = trim($_POST['password']);

include "../transit/loginPDO.php"; //still outside of root

//i use htmlentities() on $myAppUser from the db
//so i also use it on $username to avoid a mismatch
//then i don't have to worry about forgetting to escape it
//i also store a hashed password in the database
if ($username == $myAppUser && password_verify($password, $myAppUserPass)) {
  $_SESSION['userId'] = $myAppUser;
  session_regenerate_id(true); //elevation of privilege
  header("Location: ./");
  exit;
} else {
  header("Location: ../");
  exit;
}
?>

loginPDO.php

<?php
$dbn = 'user_accounts';
$host = 'localhost';
$user = 'root'; //user and pass default while developing with xampp
$pass = ''; //user and pass default while developing with xampp
$opt = array(
    PDO::ATTR_EMULATE_PREPARES => false,
    PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC
  );

try {

  $conn = new PDO("mysql:host=$host; dbname=$dbn; charset=utf8mb4", $user, $pass, $opt);
  $query = 'SELECT username, password FROM members WHERE username = :PostUser';

  $dbh = $conn->prepare($query);
  $dbh->execute(array(':PostUser' => $username));
  $results = $dbh->fetch();
    $myAppUser = htmlentities($results['username'], ENT_QUOTES, "UTF-8");
    $myAppUserPass = $results['password'];

  $dbh->closeCursor();
  $dbh = null;
  $conn = null;

} catch (PDOException $e) {
    error_log($e->getMessage());
}

?>

Thanks for the code John. I am looking over it now.

I hope it helps you. I just started trying to learn php last year and databases in February of this year. The code that i posted is my first attempt at making a login system. The code work but it needs optimized and cleaned. I’ve since changed/tweaked the code.

you should keep in mind that you will need to hash the user password and store the hash in the database before you try this code. You can test it by generating a hash via php file, then copy the hash and place it into your database manually. Then you can test the process:

$HashThisPassword = "joe.904";
$showHash = password_hash($HashThisPassword, PASSWORD_DEFAULT);
echo $showHash;

You will also have to rename variables and database column names to what you are using. I think that most people use md5 for tokens and they will insult you for using sha3-512, as i do. However, i just read a blog from a security tester that claims javascript can be used in a timing attack with md5 tokens. I stay away from md5 even with csfr tokens.

edit: I’ve also changed the username comparison to a hash_equals:

if (hash_equals($myAppUser, $username) && password_verify($password, $myAppUserPass)) {
Sponsor our Newsletter | Privacy Policy | Terms of Service