-1

A newbie IT student here trying to code my subject requirement which is a ecommerce web app. The problem that im having rn is with the login form that is written in Php. Regardless if the input that I type is right or wrong, the alert still displays "Please fill up all fields".

This is my Php Login Form

<?php
$conn = mysql_connect("localhost","root","1234");
if(!$conn)
{
    die('Could not connect: ' . mysql_error());
    }mysql_select_db("registration", $conn);
$email=$_POST["email"];
$pwd=md5($_POST["password"]);

$query = mysql_query("SELECT * FROM tbl_reg where password='$pwd' AND email='$email'",$conn);

$rows = mysql_num_rows($query);
if(!$email|| !$pwd)

    { 
    echo"<script>alert(\"please fill up fields\");window.location='sign-in.html'</script>";
    }
    if ($rows == 1)
    {
    echo"<script>alert(\"login Succes\");window.location='index2.html'</script>";
    }
    else
    {
        $error = "Username or Password is invalid";
        }
        if ($rows == 0)
        {
echo"<script>alert(\"Username or Password is Incorrect\");window.location='login.php'</script>";}
        mysql_close($conn);
?>

Here is basically my HTML Login Form

<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="Mark Otto, Jacob Thornton, and Bootstrap contributors">
    <meta name="generator" content="Hugo 0.104.2">
    <title>Log in Form</title>
    <link rel="canonical" href="https://getbootstrap.com/docs/5.2/examples/sign-in/">
<link href="assets/css/bootstrap.min.css" rel="stylesheet">
<script src="https://code.jquery.com/jquery-3.6.1.min.js" integrity="sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ=" crossorigin="anonymous"></script>
    <style>
      .bd-placeholder-img {
        font-size: 1.125rem;
        text-anchor: middle;
        -webkit-user-select: none;
        -moz-user-select: none;
        user-select: none;
      }

      @media (min-width: 768px) {
        .bd-placeholder-img-lg {
          font-size: 3.5rem;
        }
      }

      .b-example-divider {
        height: 3rem;
        background-color: rgba(0, 0, 0, .1);
        border: solid rgba(0, 0, 0, .15);
        border-width: 1px 0;
        box-shadow: inset 0 .5em 1.5em rgba(0, 0, 0, .1), inset 0 .125em .5em rgba(0, 0, 0, .15);
      }

      .b-example-vr {
        flex-shrink: 0;
        width: 1.5rem;
        height: 100vh;
      }

      .bi {
        vertical-align: -.125em;
        fill: currentColor;
      }

      .nav-scroller {
        position: relative;
        z-index: 2;
        height: 2.75rem;
        overflow-y: hidden;
      }

      .nav-scroller .nav {
        display: flex;
        flex-wrap: nowrap;
        padding-bottom: 1rem;
        margin-top: -1px;
        overflow-x: auto;
        text-align: center;
        white-space: nowrap;
        -webkit-overflow-scrolling: touch;
      }
    </style>

    
    <!-- Custom styles for this template -->
    <link href="assets/css/signin.css" rel="stylesheet">
  </head>
  <body class="text-center">
    
<main class="form-signin w-100 m-auto">

  <form method="post" action="login.php">
    <img class="mb-4" src="../assets/brand/bootstrap-logo.svg" alt="" width="72" height="57">
    <h1 class="h3 mb-3 fw-normal">Please sign in</h1>

    <div class="form-floating">
      <input type="email" class="form-control" id="floatingInput" placeholder="name@example.com" name="email">
      <label for="floatingInput">Email address</label>
    </div>
    <div class="form-floating">
      <input type="password" class="form-control" id="floatingPassword" placeholder="Password" name="password">
      <label for="floatingPassword">Password</label>
    </div>

    <div class="checkbox mb-3">
      <label>
        <input type="checkbox" value="remember-me"  > Remember me
      </label>
    </div>
    <button class="w-100 btn btn-lg btn-primary" type="submit"><a href="appDev Assignment/index.html">Sign in</a></button>
    <p class="mt-5 mb-3 text-muted">&copy; 2017–2022</p>
  </form>

<center>
  
  <p class="mt-5 mb-3 text-muted" id="q">&copy;</p>
  
</center>
</main>


<script>
  var category = 'happiness'
    $.ajax({
        method: 'GET',
        url: 'https://api.api-ninjas.com/v1/quotes?category=' + category,
        headers: { 'X-Api-Key': 'ToCfG0A/2Y9rS7AiwSj0BA==5YvMUReDisFAtJ0P'},
        contentType: 'application/json',
        success: function(result) {
            console.log(result);

            var q=result;
            var quote=result[0].quote;
            console.log(quote);

            let q1 = document.getElementById("q")
            q1.textContent =quote 
        },
        error: function ajaxError(jqXHR) {
            console.error('Error: ', jqXHR.responseText);
        }
    });
    
</script>
    
  </body>
</html>

I have a pretty shitty Prof. who just posted the syntax in a Ppt. file without any kind of information. Just pure hard code. Nothing more. nothing less. without even a sliver of teaching. I tried everything from rewriting my code to dropping my database or deleting my Table but to no avail. I even tried to rewrite everything even the HTML form one. Please i need help because our midterms are just at the end of the month and i really need help.

Shadow
  • 33,525
  • 10
  • 51
  • 64
  • 3
    Your code is wide open to SQL injection - **always** use a `prepared statement` when using user supplied data in a sql query. – Professor Abronsius Nov 13 '22 at 08:14
  • 4
    You appear to be storing user's passwords in `plain text` format within the db - **always** hash the password using `password_hash` and verify the password ( at login ) with `password_verify`. MD5 is not enough - it has been broken for years and is not considered secure – Professor Abronsius Nov 13 '22 at 08:15
  • 2
    You have no checks in place to determine **if** the posted variables exist before using them. Use `isset( $var, $var2, $var3 )` to test multiple at once – Professor Abronsius Nov 13 '22 at 08:16
  • 2
    The sql query is executed using `mysql_query` but you have not fetched the recordset - any logic that allows a user to proceed should be done on the basis f the query succeeding or failing rathert than there mere existence of a variable. – Professor Abronsius Nov 13 '22 at 08:18
  • 1
    One other thing of note - you are redirecting to a normal `.html` page so any authentication and security session info is lost immediately. There would be nothing to prevent someone going directly to those html pages and bypassing the login – Professor Abronsius Nov 13 '22 at 08:29
  • 1
    [Why shouldn't I use mysql_* functions in PHP?](https://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php?noredirect=1&lq=1) – brombeer Nov 13 '22 at 08:51
  • Thanks for the help! I'm in my 3rd year of Uni but im still crawling my way through Web development. This helps out a lot <3 –  Nov 13 '22 at 13:04

2 Answers2

2

In support of the comments made above, perhaps the following will be of help.

<?php

    # start & maintain session variables for all pages
    session_start();
    
    # enable error reporting
    error_reporting( E_ALL );
    mysqli_report( MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT );
    
    # create the mysql connection - the OO format is much less verbose!
    $conn = new mysqli('localhost','root','1234','registration)';
    
    
    # test that the request is a POST request and you have important variables set ( using `isset` )
    if( $_SERVER['REQUEST_METHOD']=='POST' && isset(
        $_POST['email'],
        $_POST['password']
    )){
        
        # create the basic sql and construct the `prepared statement`
        $sql='select `password` from `tbl_reg` where `email`=?';
        $stmt=$conn->prepare( $sql );
        # bind the placeholder(s) to variables
        $stmt->bind_param('s', $_POST['email'] );
        $stmt->bind_result( $hash );
        $stmt->execute();
        
        # if the stored hash matches the value generated by `password_verify` that is a success
        if( password_verify( $_POST['password'], $hash ) ){
        
            # OK - set a session variable to be propagated throughout entire session.
            $_SESSION['username']=$_POST['email'];
            
            # redirect to a PHP page that maintains the session
            exit( header( 'Location: index.php' ) );
        }else{
            # FAIL
            exit( header( 'Location: login.php' ) );
        }
    }

?>

And an example of using password_hash when adding your users.

/* to add the user and password - probably will have more columns/values in actual sql */
$sql='insert into `tbl_reg` ( `email`, `password` ) values ( ?, ? )';
$stmt=$conn->prepare( $sql );

$hash=password_hash( $_POST['password'], PASSWORD_DEFAULT );
$stmt->bind_param('ss', $_POST['email'], $hash );
$stmt->execute();
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46
  • Great contribution. I prefer all MySQL keywords to be written in all caps. Why do you pass `header()`'s `void` return value as the parameter of `exit()`? – mickmackusa Nov 13 '22 at 10:23
  • @mickmackusa - only reason I do the `exit` and `header` in a single line is brevity. Rather than 2 lines just the one will suffice. The return value is not important - just ensuring the script ends there. To which `mysqli` keywords do you refer? – Professor Abronsius Nov 13 '22 at 13:16
  • `SELECT`, `FROM`, `WHERE`, `INSERT INTO`, `VALUES`. ...[here's one of the debate pages](https://stackoverflow.com/q/608196/2943403) I like all caps for readability. Others don't. – mickmackusa Nov 13 '22 at 13:32
  • ah - I see what you mean. I'm in the other camp - prefer all lower case but each unto their own I guess. – Professor Abronsius Nov 13 '22 at 14:23
-1

Make Some Few Changes in Your Code and Check if your code works.

Update Code In Html File

Delete Below Line :

<button class="w-100 btn btn-lg btn-primary" type="submit"><a href="appDev Assignment/index.html">Sign in</a></button>

And Add here below line

<input type="submit" name="submit" value="Submit">

Update Code in Login.php File

if (isset($_POST['submit'])) {
  $email=$_POST["email"];
  $pwd=md5($_POST["password"]);

  $query = mysql_query("SELECT * FROM tbl_reg where password='$pwd' AND email='$email'",$conn);
  $rows = mysql_num_rows($query);

  if(!$email|| !$pwd)
      { 
        echo"<script>alert(\"please fill up fields\");window.location='sign-in.html'</script>";
      }
    elseif ($rows == 1)
      {
        echo"<script>alert(\"login Succes\");window.location='index2.html'</script>";
      }
    elseif ($rows == 0)
      {
        echo"<script>alert(\"Username or Password is Incorrect\");window.location='login.php'</script>";
      }
    else
      {
        echo $error = "Username or Password is invalid";
      }
}
        mysql_close($conn);

Note : If it still showing alert box with message "please fill up fields". Then, somehow login.php not getting input value of email & password from html file when you were submitting your form from html file.

Without Checking All this thing, i cant fix that problem by writing here..

if is there any way to continiously chat with your, then i can help your you to solve your problem.