-4

I am trying to display the errors on the same page if anyone entered invalid login details but when invalid login details are entered a message is displayed called Array? Not sure why that's happening.

In this code, there is a login form and if user logs in then log in, a success message appears but when details are invalid a message should appear "invalid details" which is not appearing

<?php
// starting session
session_start();
// calling connection
require('/home/s3022041/sqlC/dbConnect.php'); 
$message = "";
$role = "";

if($_SERVER['REQUEST_METHOD'] == "POST"){
                
    //Array to hold any errors in updated data
    $errors = array();
    
    //Checking entered email
    if(empty($_POST['username'])){
            $errors[] = "username address required";
        }
    else{
        $username = $_POST['username'];
        if(filter_var($_POST['username'], FILTER_VALIDATE_EMAIL)) {
            $username = $_POST['username'];
        } 
        else {
            $errors[] = "Invalid username";
        }
    }

    if(empty($_POST['password'])){
        $errors[] = "passwrod required";
    }
    else{
        $password = validating_input($_POST['password']);

    }

if(isset($_POST["btnLogin"]))
{
        
    $username = $_POST["username"];
    $password = $_POST["password"];

    // retrieving user data
    $query = "SELECT * FROM user WHERE username = '$username' AND password='$password'";
    // executing query
    $result = mysqli_query($connection, $query);

    if(mysqli_num_rows($result) > 0)
    {
        while($row = mysqli_fetch_assoc($result))
        {
            // if user logs in 
            if($row["role"] == "user") //|| ($row["role"] == "admin"))
            {
                //Creating session variables to hold relevant information about who is logged in
                $_SESSION['User'] = $row["username"];
                $_SESSION['Role'] == $row["role"];
                
                // redirecting to home page after 5 seconds..
                header( "refresh:5;url=index.php" );
                $text = "<h4>Welcome {$_SESSION['User']}</h4>";
                $text1 = "<h4>welcome to kiddies,</h4>";
                $text2 = "<h5>you'll be redirected  in 5 seconds...</h5>";
            }
            // if admin logs in
            elseif($row["role"] == "admin")
            {
                //Creating session variables to hold relevant information about who is logged in
                 $_SESSION['Admin'] = $row["username"];
                 $_SESSION['Role'] == $row["role"];
                
                //redirecting to home page after 5 seconds..
                header( "refresh:5;url=temp/adminDshboard.php" );
                $text = "<h4>Welcome {$_SESSION['Admin']}</h4>";
                $text1 = "<h4>welcome to kiddies,</h4>";
                $text2 = "<h5>you'll be redirected to <strong>admin panel</strong> in 5 seconds...</h5>";
            }
            
            
        }
    }
}

    else
    {
        echo "$errors";
        header("location : login.php");
    }
}



?>


<?php

include "header.php";
?>
<!doctype html>
<html lang="en">
  <head>
  <link rel="icon" type="image/png" href="images/logo_transparent.png"/>
  <link href="../assets/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css">
  <script src="//maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js"></script>
  <script src="//cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <!-- Bootstrap CSS -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-eOJMYsd53ii+scO/bJGFsiCZc+5NDVN2yr8+0RDqr0Ql0h+rP48ckxlpbzKgwra6" crossorigin="anonymous">

    <link rel="stylesheet" href="Mystyle.css">
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
 

    <style>
         .card{
            padding: 2rem;
            
        } 

          .global-container{
            margin-top: 10rem;
            margin-bottom: 5rem;
        }

        .welcome{
            padding: 3rem;
            background-color: white;
            color: black;
            font-weight: bold;
            font-family: 'Cherry Swash';
            font-size: 15rem;
        } 
    </style>
    
  </head>
  <body>

    <div class="container"> 
                    <div class="col-12 col-md-6">

                   

                         <div class="global-container">

                       

                    <?php

                    if((isset($_SESSION['Admin'])) || (isset($_SESSION['User'])))
                    {
                        echo "<div class='welcome'>$text";
                        echo "$text1";
                        echo  "$text2</div>";
                    }
                
                    else
                    
                    {
                        ?>
                            <div class="card login-form">
                                <div class="card-body">
                                    <h3 class="card-title text-center">Log in to Kiddies Cove</h3>
                                        <div class="card-text">
                                        <!--
                                        <div class="alert alert-danger alert-dismissible fade show" role="alert">Incorrect username or password.</div> -->
                                        <form method="POST" action="login.php">
                                            <!-- to error: add class "has-danger" -->
                                            <div class="form-group">
                                                <label for="exampleInputEmail1">Email address</label>
                                                <input type="email" name="username" class="form-control form-control-sm" id="exampleInputEmail1" aria-describedby="emailHelp">
                                            </div>
                                            <div class="form-group">
                                                <label for="exampleInputPassword1">Password</label>
                                                
                                                <input type="password" name="password" class="form-control form-control-sm" id="exampleInputPassword1">
                                            </div>
                                            
                                            
                                            <button type="submit" name="btnLogin" class="btn btn-primary btn-block">Sign in</button>
                                                <?php echo "<h1>$errors</h1>"; ?>
                                            <div class="sign-up">
                                                Don't have an account? <a href="registration.php">Create One</a>
                                            </div>

                                        </form>
                                        <?php
                    }
                
                    ?>
                                 </div>
                    </div>
                </div>
            </div>
        </div>
     </div>



            <?php
            //Function which  validates inputData
            function validating_input($inputData){
                $inputData = trim($inputData);
                $inputData = stripslashes($inputData);
                $inputData = htmlentities($inputData, ENT_QUOTES);
                return $inputData;
            }
            ?>
Dharman
  • 30,962
  • 25
  • 85
  • 135
Ahmed
  • 3
  • 4
  • Can you show the error? write it or add a picture – Acca Emme May 01 '21 at 18:43
  • i have no errors its just that the invalid detail message is not showing up? – Ahmed May 01 '21 at 18:44
  • 1
    **Warning:** You are wide open to [SQL Injections](https://php.net/manual/en/security.database.sql-injection.php) and should use parameterized **prepared statements** instead of manually building your queries. They are provided by [PDO](https://php.net/manual/pdo.prepared-statements.php) or by [MySQLi](https://php.net/manual/mysqli.quickstart.prepared-statements.php). Never trust any kind of input! Even when your queries are executed only by trusted users, [you are still in risk of corrupting your data](http://bobby-tables.com/). [Escaping is not enough!](https://stackoverflow.com/q/5741187) – Dharman May 01 '21 at 18:45
  • 1
    **Never store passwords in clear text or using MD5/SHA1!** Only store password hashes created using PHP's [`password_hash()`](https://php.net/manual/en/function.password-hash.php), which you can then verify using [`password_verify()`](https://php.net/manual/en/function.password-verify.php). Take a look at this post: [How to use password_hash](https://stackoverflow.com/q/30279321/1839439) and learn more about [bcrypt & password hashing in PHP](https://stackoverflow.com/a/6337021/1839439) – Dharman May 01 '21 at 18:45
  • 1
    `$errors` is an array so `echo "$errors";` makes no sense and causes error. Even if it was correct, using `echo` wouldn't make sense before `header("location : login.php");` – B001ᛦ May 01 '21 at 18:46
  • 1
    Never use functions like `validating_input`. They will damage your data. – Dharman May 01 '21 at 18:48

1 Answers1

0

I am giving simple example assuming your code is from login.php

then you can edit as per your requirement.

#it is just a example how to show errors. Data sanitization, preventing sql injection etc is not considered in this example.

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

 $error = false;

 if((isset$_POST['action']) && ($_POST['action']=="loginnow")){
     $username = $_POST['username'];
     $password = $_POST['password'];

      if(empty($usernane)){
               $error= true;
               $msg[]= " Enter Username";
      }
      if(empty($password)){
               $error= true;
               $msg[] = "Enter Password";
       }
      if (!$error){
           // check if username and password matches and redirect to index.php. successfully login
      }else{
               $msg[] = " Invalid Username or Password";
      }

   }
   ?>

in html body, above your form, put

   <?php
       if(isset($msg)){
            foreach($msg as $err)[
                  echo $err."<br>";
        }
      }
     ?>


 <form method="post" action="">
     <input type="hidden" name="action" value="loginnow">

     Username : <input type="text" name="username">
     Password : <input type="password" name="password">

     <input type="submit" name="submit"  value="Log In">
 </form>