-1

Hello I'm new to PHP and I am trying to make a simple login and register function for the user. Once user registers, his details will be added into the database so he can login. But now even though his username & pw are correct it does not login.

Here is my code:

<?php
if(!empty($_POST['username']) && !empty($_POST['password']))
{
    $username = mysql_real_escape_string($_POST['username']);
    $password = md5(mysql_real_escape_string($_POST['password']));

    $checklogin = mysql_query("SELECT * FROM admin WHERE Username = '".$username."' AND Password = '".$password."'");

    if(mysql_num_rows($checklogin) == 1)
    {
          $row = mysql_fetch_array($checklogin);
          $email = $row['Email_Address'];

          $_SESSION['Username'] = $username;
          $_SESSION['Email_Address'] = $email;
          $_SESSION['LoggedIn'] = 1;

          echo "<h1>Success</h1>";
          echo "<p>We are now redirecting you to the member area.</p>";
          echo "<meta http-equiv='refresh' content='=2;index2.php' />";
          header("Location: Home.php");
    }
    else
    {
          echo "<h1>Error {$password}</h1>";
          echo "<p>Sorry, your account could not be found. Please <a href=\"index2.php\">click here to try again</a>.</p>";
    }
}
else
{?>
    <h1>Member Login</h1>
    <p>Please either login below, or <a href="register2.php">click here to register</a>.</p>
        <form method="post" action="index2.php" name="loginform" id="loginform">
        <fieldset>
                <label for="username">Username:</label><input type="text" name="username" id="username" /><br />
                <label for="password">Password:</label><input type="password" name="password" id="password" /><br />
                <input type="submit" name="login" id="login" value="Login" />
        </fieldset>
        </form>
<?php }?>

Any help is appreciated

Nana Partykar
  • 10,556
  • 10
  • 48
  • 77
  • 3
    You should not be using mysql_* functions and you should not be using md5() for passwords. We've got that out of the way, how are you saving those users? Are you sure you're encoding the passwords the same way when storing them into the database? – Andrius Nov 16 '15 at 09:35
  • echo your query like `echo SELECT * FROM admin WHERE Username = '".$username."' AND Password = '".$password."'"; die` then run the file and copy the query and check the same in mysql..... let me know. – Kausha Mehta Nov 16 '15 at 09:36
  • 2
    I strongly recommend reading "[The definitive guide to form-based website authentication](https://stackoverflow.com/questions/549/the-definitive-guide-to-form-based-website-authentication)". – Hexaholic Nov 16 '15 at 09:37
  • please show your database md5 code for password and your login md5 code of password – LOKESH Nov 16 '15 at 09:40
  • @Andrius I'm using md5 because it's just very basic encryption for my assignment. I think I am because i've compared the $password with the md5 of the $password – Jasmine Montez Nov 16 '15 at 09:44
  • @KaushaMehta 40d67f2de5440067ecd66deb3793442f this is what you mean? – Jasmine Montez Nov 16 '15 at 09:44
  • No, execute the whole query in mysql and check what is the output. – Kausha Mehta Nov 16 '15 at 09:52
  • the output shows all the username, password and email address that has been stored in my database @KaushaMehta – Jasmine Montez Nov 16 '15 at 10:05
  • What query you fire in mysql? I said execute the query whatever echo after enter the username and password and submit. – Kausha Mehta Nov 16 '15 at 10:07
  • Do you store the password, in the `admin` table, in a pre-hashed `md5` form or plain text? – Professor Abronsius Nov 16 '15 at 10:30

1 Answers1

0

As was noted in a comment you really ought to be using either mysqli or PDO ~ the mysql extensions are now deprecated and offer little in terms of security against the dreaded sql injection attacks. The code below uses mysqli and has been tested using both a plain text password ( as is currently shown ) and an md5 hashed version.

If your db stores the user's password in a pre-hashed md5 form then set $prehashed=true

<?php
    session_start();
    $errors=array();
    $prehashed=false;


    if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['username'], $_POST['password'] ) ){

        /* Your db connection settings: change as appropriate */
        $host   =   'localhost';
        $uname  =   'xxx'; 
        $pwd    =   'xxx'; 
        $db     =   'xxx';

        /* create mysqli object */
        $conn   =   new mysqli( $host, $uname, $pwd, $db );

        /* Create and prepare the sql */
        $sql    =   'select `username`,`email` from `admin` where `username`=? and `password`=?';
        $stmt   =   $conn->prepare( $sql );

        /* Bind the placeholders to the desired fields */
        $stmt->bind_param( 'ss', $username, $password );

        /* Populate the variables with POST data - with some minor filtering */
        $username   =   trim( strip_tags( filter_input( INPUT_POST, 'username', FILTER_SANITIZE_STRING ) ) );
        $password   =   trim( strip_tags( filter_input( INPUT_POST, 'password', FILTER_SANITIZE_STRING ) ) );

        /* Pre-hased MD5 password?  */
        if( $prehashed ) $password = md5( $password );



        /* Execute the query */
        $result     =   $stmt->execute();
        $stmt->bind_result( $user, $email );


        /* If there is a match, set session vars and redirect */
        if( $result ){
            /* Get the records */
            $stmt->fetch();

            /* success? */
            if( isset( $user, $email ) ){

                $_SESSION['Username'] = $user;
                $_SESSION['Email_Address'] = $email;
                $_SESSION['LoggedIn'] = 1;

                $conn->close();

                header( 'location: home.php?username='.$user.'&email='.$email );
            } else {
                $conn->close();
                $errors[]='<h1>Error</h1>';
                $errors[]='<p>Sorry, your account could not be found. Please try again.</p>';
            }

        } else {
            /* There was some sort of error, display results below form */
            $conn->close();
            $errors[]='<h1>Error</h1>';
            $errors[]='<p>Sorry, your account could not be found. Please try again.</p>';

        }
    }
?>
<!doctype html>
<html>
    <head>
        <title>Member login</title>
        <style>
            form{
                width:50%;
                float:none;
                margin:1rem auto;   
            }
            label{
                display:block;
                width:80%;
                float:none;
                clear:both;
                margin:1rem auto;
                box-sizing:content-box; 
                padding:1rem;   
            }
            label:before{
                display:inline-block;
                clear:none;
                float:left;
                width:20%;

                content:attr(for)": ";
            }
            label > input{
                clear:none;
                float:left;
                display:block;
            }
        </style>
    </head>
    <body>

        <form method="post" name="loginform" enctype='application/x-www-form-urlencoded'>
            <h1>Member Login</h1>
            <p>Please either login below, or <a href="register2.php">click here to register</a>.</p>
            <fieldset>
                <label for="Username"><input type="text" name="username" id="username" /></label>
                <label for="Password"><input type="password" name="password" id="password" /></label>
                <input type="submit" name="login" id="login" value="Login" />
            </fieldset>
            <?php
                if( $_SERVER['REQUEST_METHOD']=='POST' && isset( $_POST['username'], $_POST['password'] ) ){
                    if( !empty( $errors ) ) echo implode( PHP_EOL, $errors );
                }
            ?>
        </form>
    </body>
</html>
Professor Abronsius
  • 33,063
  • 5
  • 32
  • 46