0

I am trying to do a login page in php, and I have no errors, but it says "username missing" and "password missing" even if they aren't. here is my code, what I am doing wrong?

connection.php

<?php
$mysql_hostname = "localhost";
$mysql_user = "root";
$mysql_password = "";
$mysql_database = "simple_login";
$prefix = "";
$bd = mysqli_connect($mysql_hostname, $mysql_user, $mysql_password, $mysql_database) or die("Could not connect database");
?>

login_exec.php

<?php
    //Start session
    session_start();

    //Include database connection details
    require_once('connection.php');

    //Array to store validation errors
    $errmsg_arr = array();

    //Validation error flag
    $errflag = false;

    //Function to sanitize values received from the form. Prevents SQL injection
    function clean($bd,$str) {
        $str = @trim($str);
        if(get_magic_quotes_gpc()) {
            $str = stripslashes($str);
        }
        return mysqli_real_escape_string($bd, $str);
    }

    //Sanitize the POST values
    $username = clean($_POST['username']);
    $password = clean($_POST['password']);

    //Input Validations
    if($username == '') {
        $errmsg_arr[] = 'Username missing';
        $errflag = true;
    }
    if($password == '') {
        $errmsg_arr[] = 'Password missing';
        $errflag = true;
    }

    //If there are input validations, redirect back to the login form
    if($errflag) {
        $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
        session_write_close();
        header("location: index.php");
        exit();
    }

    //Create query
    $qry="SELECT * FROM member WHERE username='$username' AND password='$password'";
    $result=mysqli_query($bd, $qry);

    //Check whether the query was successful or not
    if($result) {
        if(mysqli_num_rows($result) > 0) {
            //Login Successful
            session_regenerate_id();
            $member = mysqli_fetch_assoc($result);
            $_SESSION['SESS_MEMBER_ID'] = $member['mem_id'];
            $_SESSION['SESS_FIRST_NAME'] = $member['username'];
            $_SESSION['SESS_LAST_NAME'] = $member['password'];
            session_write_close();
            header("location: home.php");
            exit();
        }else {
            //Login failed
            $errmsg_arr[] = 'user name and password not found';
            $errflag = true;
            if($errflag) {
                $_SESSION['ERRMSG_ARR'] = $errmsg_arr;
                session_write_close();
                header("location: index.php");
                exit();
            }
        }
    }else {
        die("Query failed");
    }
?>

home.php

<?php
    //require_once('auth.php');
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<title>Untitled Document</title>
<style type="text/css">
<!--
.style1 {
    font-size: 36px;
    font-weight: bold;
}
-->
</style>
</head>

<body>
<p align="center" class="style1">Login successfully </p>
<p align="center">This page is the home, you can put some stuff here......</p>
<p align="center"><a href="index.php">logout</a></p>
</body>
</html>

and index.php

<?php
    //Start session
    session_start();    
    //Unset the variables stored in session
    unset($_SESSION['SESS_MEMBER_ID']);
    unset($_SESSION['SESS_FIRST_NAME']);
    unset($_SESSION['SESS_LAST_NAME']);
?>
<html>
<body>
<form name="loginform" action="login_exec.php" method="post">
<table width="309" border="0" align="center" cellpadding="2" cellspacing="5">
  <tr>
    <td colspan="2">
        <!--the code bellow is used to display the message of the input validation-->
         <?php
            if( isset($_SESSION['ERRMSG_ARR']) && is_array($_SESSION['ERRMSG_ARR']) && count($_SESSION['ERRMSG_ARR']) >0 ) {
            echo '<ul class="err">';
            foreach($_SESSION['ERRMSG_ARR'] as $msg) {
                echo '<li>',$msg,'</li>'; 
                }
            echo '</ul>';
            unset($_SESSION['ERRMSG_ARR']);
            }
        ?>
    </td>
  </tr>
  <tr>
    <td width="116"><div align="right">Username</div></td>
    <td width="177"><input name="username" type="text" /></td>
  </tr>
  <tr>
    <td><div align="right">Password</div></td>
    <td><input name="password" type="text" /></td>
  </tr>
  <tr>
    <td><div align="right"></div></td>
    <td><input name="" type="submit" value="login" /></td>
  </tr>
</table>
</form>
</body>
</html>
AndrB
  • 33
  • 7
  • for the sake of completeness please post also the code of your login `
    `.
    – CodeBrauer Jun 14 '16 at 08:27
  • I just copied the part of your script that is responsible for you validation. This works pretty fine - see the result here: https://3v4l.org/D9U56 – CodeBrauer Jun 14 '16 at 08:30
  • also added index.php, sorry – AndrB Jun 14 '16 at 08:31
  • @CodeBrauer, then what is wrong? I am trying to take the username and password from my db – AndrB Jun 14 '16 at 08:33
  • I've added the answer that should solve your problem. – CodeBrauer Jun 14 '16 at 08:37
  • 1
    You need to pass your database link (*$bd*) to the mysqli_query `$result=mysqli_query($bd, $qry);` – Matt Jun 14 '16 at 08:43
  • 1
    Off topic, but I notice that your code includes `get_magic_quotes_gpc()` and `stripslashes()`. Please note that if you're using any currently supported PHP version (v5.4 and up), this code is unnecessary as the magic quotes feature was removed from PHP in v5.4. The `get_magic_quotes_gpc()` still exists in newer versions but always returns false. – Simba Jun 14 '16 at 08:49
  • @Matt, I did it and now I have this errors: Notice: Undefined variable: bd in C:\xampp\htdocs\login\login_exec.php on line 24 Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\login\login_exec.php on line 24 Notice: Undefined variable: bd in C:\xampp\htdocs\login\login_exec.php on line 24 Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\login\login_exec.php on line 24 – AndrB Jun 14 '16 at 09:16
  • Is it a typo on your connection.php on your question and should be `$db`? This notice means it doesn't know what `$bd` is. – Matt Jun 14 '16 at 09:21
  • it appears $bd everywhere. – AndrB Jun 14 '16 at 09:27
  • Ahhh okay you need to pass the database link into your custom function, add this `function clean ($bd, $str) {}` – Matt Jun 14 '16 at 09:33
  • Can you also update your code on your question to keep it up to date. Thanks – Matt Jun 14 '16 at 09:34
  • And then on your `$username = clean ()` pass the `$bd` variable in so you have `$username = clean ($bd, $_POST ['username'])` similarly for password – Matt Jun 14 '16 at 09:37
  • it works. thank you @Matt – AndrB Jun 14 '16 at 10:10
  • 1
    Great. Glad it works; go ahead and mark CodeBrauer answer as accepted since it contains pretty much all the info. @CodeBrauer if you edit it to contain the passing of `$bd` as a parameter rather than making it global then your answer is what worked for op. – Matt Jun 14 '16 at 10:14

2 Answers2

3

Here is your bug:

function clean($str) {
    $str = @trim($str);
    if(get_magic_quotes_gpc()) {
        $str = stripslashes($str);
    }
    return mysqli_real_escape_string($str); # <-- BUG!
}

mysqli_real_escape_string expects 2 parameters. Your code is written in procedural style so you have to pass:

  1. the mysqli link/resource
  2. the string to escape

So this function must be extended this way:

function clean($bd, $str) { //new
    $str = @trim($str);
    if(get_magic_quotes_gpc()) {
        $str = stripslashes($str);
    }
    return mysqli_real_escape_string($bd, $str); //new
}

In your case mysqli_real_escape_string probably returns NULL, false or an empty string - what causes the error messages.


Edit:

You're missing also a param on mysqli_query. You have to pass the link as first param. So the function knowns on what connection it should be executed.


Also you should check some of this topics, to make your login more secure:

Community
  • 1
  • 1
CodeBrauer
  • 2,690
  • 1
  • 26
  • 51
  • I changed that, but it still doesn't work. whatever I write there, it says usrname and password missing. :| – AndrB Jun 14 '16 at 08:39
  • how can I check that? – AndrB Jun 14 '16 at 08:41
  • Your should have a message (warning) already without the bugfix, that mysqli_real_escape_string is missing one param. If not - paste this at the top of each file: `ini_set('display_errors', 'On');error_reporting(E_ALL);` or change your server configs. – CodeBrauer Jun 14 '16 at 08:43
  • it didn't display the message with one param is missing. I put the code on each file, and it stil doesn't show me the errors. but at the other projects it did... – AndrB Jun 14 '16 at 08:46
  • Found the next bug. I've edited the answer - I've copied your code and it works fine for me. – CodeBrauer Jun 14 '16 at 08:49
  • it showed me nothing because I told the program to go straight to index.php. so it went to index.php and didn't display the errors. now it does they are: Notice: Undefined variable: bd in C:\xampp\htdocs\login\login_exec.php on line 30 Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\login\login_exec.php on line 30 Notice: Undefined variable: bd in C:\xampp\htdocs\login\login_exec.php on line 30 Warning: mysqli_real_escape_string() expects parameter 1 to be mysqli, null given in C:\xampp\htdocs\login\login_exec.php on line 30 – AndrB Jun 14 '16 at 09:03
  • i also did the connection on login_exec.php, and wrote global before $bd. now I have: Parse error: syntax error, unexpected '=', expecting ',' or ';' in C:\xampp\htdocs\login\login_exec.php on line 8 – AndrB Jun 14 '16 at 09:04
  • no you have to insert `global $bd;` just in the function, not in db_conncetion.php. Only there like in my answer. Than edit it like in the comment of @Matt and you should be ready to go. – CodeBrauer Jun 14 '16 at 09:12
0

on page load $username is being set to $_POST["username"] that doesn't exist. you have to validate if the form is posted

if( isset($_POST["username"]) && isset($_POST["password"]) ) 
// or
if(count($_POST))