0

For the login screen, I have done some small validation. Now the problem is I don't know how to bring the validation error msg

Please refer the else section, where the error message is mentioned.

Eg: Error message is "Invalid Username and Password Combination" when the user provides invalid username and password

<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="icon" type="img/png" href="pic/logo3.png">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body id="loginform">
<?php


$servername = "localhost";
$username = "root";
$password = "";
$dbname = "";

$conn = new mysqli($servername, $username, $password, $dbname);

if (isset($_POST['submit']))
{
$name = $_POST['name'];
$pass =$_POST['pass'];

$query      = mysqli_query($conn,"SELECT * FROM admin_user WHERE name='$name' and pass='$pass'") or die(mysqli_error());
$row        = mysqli_fetch_row($query);

if ($row) 
{           

if (isset($_POST['remember'])) {
setcookie('name', time()+60*60*7);
}
session_start();
$_SESSION['name'] = $name;
header('location:index.php');
}
else
{

echo '<div class="col-sm-12 text-align--center error">'.'Invalid Username and Password Combination'.'</div>';
}

}
?>
<div class="col-sm-6 align-center loginForm">
<img src="pic/logo.png">
<div class="box">
<form action="" method="post" name="login" class="boxContent">
<label>Username</label><br>
<input class="login-input" type="text" name="name" /><br>
<label>Password</label><br>
<input class="login-input" type="password" name="pass" /><br>
<input class="login-input m-bottom" name="submit" type="submit" value="Login"/>
<input class="bump-left" type="checkbox" name="remember"><label>Remember me</label><br>
</form><br>
<div class="forgot">
<a class="bump-left" href="">Forgot Your Password?</a>
</div>
</div>
</div>
<div class="col-sm-6 col-pad--none">
<div class="bgcontent"><img src="pic/services2.jpg"></div>
</div>
</body>
</html>
Stenal P Jolly
  • 491
  • 4
  • 15
mishal
  • 63
  • 10
  • [Little Bobby](http://bobby-tables.com/) says ***[your script is at risk for SQL Injection Attacks.](http://stackoverflow.com/questions/60174/how-can-i-prevent-sql-injection-in-php)*** Learn about [prepared](http://en.wikipedia.org/wiki/Prepared_statement) statements for [MySQLi](http://php.net/manual/en/mysqli.quickstart.prepared-statements.php). Even [escaping the string](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Apr 10 '17 at 12:05
  • 1
    **Never store plain text passwords!** Please use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. If you're using a PHP version less than 5.5 you can use the `password_hash()` [compatibility pack](https://github.com/ircmaxell/password_compat). Make sure you ***[don't escape passwords](http://stackoverflow.com/q/36628418/1011527)*** or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard Apr 10 '17 at 12:05
  • `mysqli_error()` requires the connection - `mysqli_error($conn)`. – Jay Blanchard Apr 10 '17 at 12:05
  • 1
    Assign the error message to a variable and then echo that variable in the location you wish it to appear. – Jay Blanchard Apr 10 '17 at 12:07
  • You just checked form submission. I didn't see your code for validating name and pass – manian Apr 10 '17 at 12:16
  • i can assign a variable and echo but the problem when i do this is, it will always be invoked in the place where i echod – mishal Apr 10 '17 at 12:17
  • i need this error only when my username and password is wrong – mishal Apr 10 '17 at 12:18
  • mysqli_query($conn,"SELECT * FROM admin_user WHERE name='$name' and pass='$pass'") – mishal Apr 10 '17 at 12:20
  • it check the match between username and password and log in – mishal Apr 10 '17 at 12:21
  • You are also mixing procedural and Object Oriented styles – Masivuye Cokile Apr 10 '17 at 12:26
  • Could not understand what you need since you already have the error message at the top. It's not showing you the error message? – manian Apr 10 '17 at 12:29
  • it is showing at the top of the page... but i need it under my form – mishal Apr 10 '17 at 12:46
  • @mishal you have answers below – Masivuye Cokile Apr 10 '17 at 13:01

3 Answers3

1

Please read the comments above from Jay and take them into consideration and apply what is suggested as it is very important in securing your application

Now back to your question you need to store the error message in a variable then just echo that variable where you want the message to show.

<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="icon" type="img/png" href="pic/logo3.png">
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="css/style.css">
</head>
<body id="loginform">
<?php

$loginError = "";
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "";

$conn = new mysqli($servername, $username, $password, $dbname);

if (isset($_POST['submit']))
{
$name = $_POST['name'];
$pass =$_POST['pass'];

$query      = mysqli_query($conn,"SELECT * FROM admin_user WHERE name='$name' and pass='$pass'") or die(mysqli_error());
$row        = mysqli_fetch_row($query);

if ($row) 
{           

if (isset($_POST['remember'])) {
setcookie('name', time()+60*60*7);
}
session_start();
$_SESSION['name'] = $name;
header('location:index.php');
}
else
{

$loginError = '<div class="col-sm-12 text-align--center error">Invalid Username and Password Combination</div>';
}

}
?>
<div class="col-sm-6 align-center loginForm">
<img src="pic/logo.png">
<div class="box">

    <?php echo $loginError;?> <!-- error will display here -->
<form action="" method="post" name="login" class="boxContent">
<label>Username</label><br>
<input class="login-input" type="text" name="name" /><br>
<label>Password</label><br>
<input class="login-input" type="password" name="pass" /><br>
<input class="login-input m-bottom" name="submit" type="submit" value="Login"/>
<input class="bump-left" type="checkbox" name="remember"><label>Remember me</label><br>
</form><br>
<div class="forgot">
<a class="bump-left" href="">Forgot Your Password?</a>
</div>
</div>
</div>
<div class="col-sm-6 col-pad--none">
<div class="bgcontent"><img src="pic/services2.jpg"></div>
</div>
</body>
</html>

Edit :

Putting everything together from the users comments above :

Little Bobby says your script is at risk for SQL Injection Attacks. Learn about prepared statements for MySQLi. Even escaping the string is not safe! Or PDO,

To solve the above you need to use prepared statements, you have two options, 1 use mysqli prepared or use PDO prepared statements, there are many arguments as to which one is better than the other comparison available on the internet, quick comparison here

I honestly prefer PDO.

Never store plain text passwords! Please use PHP's built-in functions to handle password security. If you're using a PHP version less than 5.5 you can use the password_hash() compatibility pack. Make sure you don't escape passwords or use any other cleansing mechanism on them before hashing. Doing so changes the password and causes unnecessary additional coding.

Therefore a solution for the above is to use password_hash() and password_verify();

See more about password hash and verify here :

So what you need to do now when you inserting the data in your database from the register page, you need to have a hash

$hash = password_hash($_POST['password'],PASSWORD_DEFAULT); Then you will need to store the hashed password in the database which is `$hash()`

This is how you login should look with PDO and password_verify()

<?php
session_start();

/*PDO Connection*/
$host    = 'localhost';
$db      = 'YOURDATABASE';
$user    = 'root';
$pass    = 'YOURPASSWORD';
$charset = 'utf8';

$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$opt = [
        PDO::ATTR_ERRMODE            => PDO::ERRMODE_EXCEPTION,
        PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
        PDO::ATTR_EMULATE_PREPARES   => false,
        ];

$dbh = new PDO($dsn, $user, $pass, $opt);

if (isset($_POST['submit'])) {

    $name = $_POST['name'];
    $pass = $_POST['pass'];

    $LoginMessage = "";

    $stmt    = $pdo->prepare("SELECT * FROM admin_user WHERE name = ?");
    $stmt->execute([$name]);
    $results = $stmt->fetch();

    if ($results && password_verify($_POST['pass'], $results['pass'])) {
        $_SESSION['name'] = $name;
        header('location:index.php');
    } else {
        $loginError = "<div class=\"col-sm-12 text-align--center error\">Invalid Username and Password Combination</div>";
    }
}

?>
<div class="col-sm-6 align-center loginForm">
<img src="pic/logo.png">
<div class="box">

    <?php echo $loginError;?> <!-- error will display here -->
<form action="" method="post" name="login" class="boxContent">
<label>Username</label><br>
<input class="login-input" type="text" name="name" /><br>
<label>Password</label><br>
<input class="login-input" type="password" name="pass" /><br>
<input class="login-input m-bottom" name="submit" type="submit" value="Login"/>
<input class="bump-left" type="checkbox" name="remember"><label>Remember me</label><br>
</form><br>
<div class="forgot">
<a class="bump-left" href="">Forgot Your Password?</a>
</div>
</div>
</div>
<div class="col-sm-6 col-pad--none">
<div class="bgcontent"><img src="pic/services2.jpg"></div>
</div>
</body>
</html>
Masivuye Cokile
  • 4,723
  • 3
  • 16
  • 33
0

/* please try below working sample code, I have added some security patches too */

$servername = "localhost";
$username = "root";
$password = "";
$dbname = "";  /* database name */
$errorMessage = "";
$conn = new mysqli($servername, $username, $password, $dbname);
if(isset($_POST['submit'])){
    $name = isset($_POST['name']) ? mysqli_real_escape_string($conn, trim($_POST['name'])) : ""; /* Escapes special characters in a string */ 
    $pass = isset($_POST['pass']) ? mysqli_real_escape_string($conn, trim($_POST['pass'])) : "";  /* Escapes special characters in a string */ 
    if($name != "" AND $pass != ""){ /* check name and pass for not empty */
        $query      = mysqli_query($conn,"SELECT * FROM admin_user WHERE name='$name' and pass='$pass'") or die(mysqli_error());
        $row        = mysqli_fetch_row($query);
        if ($row){
            if (isset($_POST['remember'])) {
                setcookie('name', time()+60*60*7);
            }
            session_start();
            $_SESSION['name'] = $name;
            header('location:index.php?sdfsdf');
        }else{
            $errorMessage = '<div class="col-sm-12 text-align--center error">Invalid Username and Password Combination</div>';
        }
    }else{
        $errorMessage = '<div class="col-sm-12 text-align--center error">Invalid Username and Password Combination</div>';
    }
}
echo $errorMessage;  /* place it anywhere you want */
  • Why should the OP try this?. A ***good answer*** will always have an explanation of what was done and why it was done in such a manner, not only for the OP but for future visitors to SO. – Jay Blanchard Apr 10 '17 at 12:45
  • Let's not teach/propagate sloppy and dangerous coding practices. If you post an answer without prepared statements [you may want to consider this before posting](http://meta.stackoverflow.com/q/344703/). Additionally [a more valuable answer comes from showing the OP the right method](https://meta.stackoverflow.com/a/290789/1011527). – Jay Blanchard Apr 10 '17 at 12:45
  • Make sure you ***[don't escape passwords](http://stackoverflow.com/q/36628418/1011527)*** or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard Apr 10 '17 at 12:46
  • Even [escaping strings](http://stackoverflow.com/questions/5741187/sql-injection-that-gets-around-mysql-real-escape-string) is not safe! – Jay Blanchard Apr 10 '17 at 12:47
0

First, instead of echo, you should pass the message into a variable, such as:

$tempMessage = "Invalid Username and Password Combination";

And then on your HTML

<?php if (isset($tempMessage)) : ?>
    <div class="yourClass">
        <?=$tempMessage?>
    </div>
<?php endif ?>

Or you can store it in a Session variable, so that you can count bad login attemps, and etc.

Rüzgar
  • 811
  • 7
  • 19