-1

I have a problem. I am building my own login page and i have some troubles. When i test my page and I insert invalid username and password code works great. But when I insert data that exists in database it just skips the if(isset($_POST['but_submit'])) part. What could be wrong here? Here's my code:

PHP:

  <?php include ("config.php");

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

     $uname = mysqli_real_escape_string($con,$_POST['txt_uname']);
     $password = mysqli_real_escape_string($con,$_POST['txt_pwd']);

     if ($uname != "" && $password != ""){

         $sql_query = "select count(*) as cntUser from users where Username='".$uname."' and passwrd='".$password."'";
         $result = mysqli_query($con,$sql_query);
         $row = mysqli_fetch_array($result);

         $count = $row['cntUser'];

         if($count > 0){

             $_SESSION['uname'] = $uname;

             header('Location: welcome.php');
         }else{
             echo "Invalid username and password";
         }

     } }

 ?>

HTML

<div class="container">
            <form method="post" action="">
            <div id="div_login">
                <h1>Login</h1>
                    <div>
                        <input type="text" class="textbox" id="txt_uname" name="txt_uname" placeholder="Username" />
                    </div>
                    <div>
                        <input type="password" class="textbox" id="txt_uname" name="txt_pwd" placeholder="Password"/>
                    </div>
                    <div>
                        <input type="submit" value="Submit" name="but_submit" id="but_submit" />
                    </div>
                </div>
            </form>
        </div>

I would be really happy somebody could help me :) Thank you!

Funk Forty Niner
  • 74,372
  • 15
  • 66
  • 132
Gandalf
  • 7
  • 5
  • What do you mean it `skips if(isset($_POST['but_submit']))`? You get no output? You should not store plain text passwords. – user3783243 Nov 17 '18 at 14:56
  • `header('Location: welcome.php');` needs `exit();` after it – Jaquarh Nov 17 '18 at 15:10
  • When i insert valid data, program gives false at `if(isset($_POST['but_submit']))`. And yes I know i shouldn't store passwords like that..I will change it after i find out what is wrong here... thank you – Gandalf Nov 17 '18 at 15:19
  • Jaquarh, thanks, bit it's still not working. – Gandalf Nov 17 '18 at 15:20
  • what does `mysqli_error($con)` return after adding that to the query? And error reporting for PHP. http://php.net/manual/en/function.error-reporting.php @Gandalf Sidenote: Use `@the_member_name` to ping directly. – Funk Forty Niner Nov 17 '18 at 16:33

1 Answers1

1

Perhaps this will work? Debug if there are fields missing first and then do your SQL.

require_once 'config.php';

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

if (mysqli_connect_errno()) die(mysqli_connect_error());

# Debug what the issue is
foreach(array('but_submit', 'txt_uname', 'txt_pwd') as $arg)
    if(!isset($_POST[$arg]))
        die("{$arg} field is not set or empty");

# Prevent SQL injection
$stmt = $con->prepare("SELECT COUNT(*) as cntUser FROM users WHERE Username ? AND passwrd = ?");
$stmt->bind_param("ss", $_POST['txt_uname'], $_POST['txt_pwd']);
if(!$stmt->execute()){ mysqli_error($con); }
$stmt->store_result();

# Check the row count is more than 0
if($stmt->num_rows != 0) {
    session_start(); # Start session, if config.php already does this you can remove this
    $_SESSION['uname'] = $_POST['txt_uname']; # Think about injects here - use the database record not untrusted POST data
    header('Location: ' . sprintf("%s://%s/welcome.php", isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != 'off' ? 'https' : 'http', $_SERVER['SERVER_NAME']));
    exit();
}

# Nothing was returned
die('Incorrect username / password combination');

Things to note, you shouldn't store the username in the session, this should be a token to which username is given as an argument in your case:

$_SESSION['token'] = \Firebase\JWT\JWT::encode(array('username' => $_POST['uname']), 'your secret');

Then inside your Welcome.php file, you can decode it like so (suggested to build some sort of controller which does this prior):

$user = \Firebase\JWT\JWT::decode($_SESSION['token'], 'your secret', array('HS256'));
echo $user['username'];

Another thing to note is its probably best to get the data out the database so you can use their unique ID to create a token along with other identities you wish you include (keep away from sensitive info).

Funk Forty Niner
  • 74,372
  • 15
  • 66
  • 132
Jaquarh
  • 6,423
  • 5
  • 27
  • 66
  • `mysqli_real_escape_string()` requires a connection as the first argument. But, I can't see why you'd suggest `$_SESSION['uname'] = mysqli_real_escape_string($_POST['txt_uname']);`, there's no need for it. – Funk Forty Niner Nov 17 '18 at 16:32
  • Well pointed out, only reason I put it in there is to stop injections into the session like XSS, but if done right, he could easily query the database and use the record in the database which is known to contain no injections if using prepared statements but ill edit this out now @FunkFortyNiner – Jaquarh Nov 17 '18 at 16:34
  • I'd change the `$stmt->execute();` to an `if(!$stmt->execute()){ mysqli_error($con); }` so that it can throw possible errors. – Funk Forty Niner Nov 17 '18 at 16:36
  • Feel free to update and change where applicable, I'm not an Mysqli_* expert, I use PDO so most of this was resourced from the manual as I answered @FunkFortyNiner – Jaquarh Nov 17 '18 at 16:37
  • Ok. Firstly thank you for your answer. I get that my submit button is not set or empty and I'm not sure how to fix this... Any suggestions? – Gandalf Nov 17 '18 at 17:58