-4

My PHP login system doesn't work. My dbms is: phpMyAdmin. The connection is done in a different 'include' file. But I can't spot where and why my login system doesn't work.

html form:

<form id="form" action='index.php' method='post' enctype="multipart/form=data">
    Username: <input type='text' name='liusername'>
    Password: <input type='password' name='lipassword'>

    <input type='submit' value='Login'  name="lisubmit">
</form>

php code:

<?php

    isset ($_POST ['lisubmit']) {

        // Run the log in script here 
        $username = strip_tags($_POST['liusername']);
        $password = strip_tags($_POST['lipassword']);

        //find the record in database that corresponds to this user
        $query = "SELECT user_id, user_password FROM user WHERE user_username = '".$_POST['liusername']."'";

        //test to see if the password from the form is dame in database
        if ($row['user_password'] == $_POST ['lipassword'] && $row['user_username'] == $_POST ['liusername']) {
            $_SESSION ['loggedin'] = true;
            $_SESSION ['id'] = $row['user_id];
        } else {
            $_SESSION['loggedin'] = false;
            $_SESSION ['id'] = 0;
        }

        if ($_SESSION ['logginin') == true) {
            echo "<p>You are loggin in</p>\n";
        } else {
            echo "<p>You are NOT logged in</p>\n";
        }

?>

database connection file:

<?php

    session_start();
    $hostname = "localhost";
    $dbusername = "root";
    $dbpassword = "";   
    $dbase = "assignment";

    mysql_connect($hostname, $dbusername, $dbpassword) or die(mysql_error());

    mysql_select_db($dbase) or die(mysql_error());

?>
Rizier123
  • 58,877
  • 16
  • 101
  • 156
user3545833
  • 99
  • 1
  • 2
  • 8
  • 5
    You forgot to execute the query. – Abhik Chakraborty Apr 21 '15 at 11:03
  • your `$_SESSION ['id'] = $row['user_id];` should `$_SESSION ['id'] = $row['user_id'];` need single quotes :) – Eko Junaidi Salam Apr 21 '15 at 11:04
  • Yeah, phpMyAdmin database is great. – Lukas Hajdu Apr 21 '15 at 11:04
  • Forget to run query and never use plain passwords use this tutorial for password hashing: http://www.phpgang.com/how-to-hashing-password-in-php-5-5-with-password-hashing-api_458.html – Huzoor Bux Apr 21 '15 at 11:05
  • What mysql function are you using? `mysqli` or `PDO`? – TheSk8rJesus Apr 21 '15 at 11:05
  • 1
    `strip_tags()` is NOT sufficient to prevent SQL Injections since it only removes php or html tags, but not malicious SQLs like `; DROP users`. Use `filter_var()` or `htmlspecialchars()` to prevent sql injections. – Realitätsverlust Apr 21 '15 at 11:07
  • then an `=` sign in `enctype="multipart/form=data"` between form and data which should be a hyphen. you need to check for errors when coding. did you start the session? quite a few things wrong with this. we don't even know which MySQL API you're using to connect with. – Funk Forty Niner Apr 21 '15 at 11:09
  • @TheSk8rJesus I used mysql_connect – user3545833 Apr 21 '15 at 11:14
  • Along all the other mistakes the people found, at line: `if ($_SESSION ['logginin') == true)` you have a `)` instead of a `]`. So it should be: `if ($_SESSION ['logginin'] == true)`. Off topic note: 'You are loggin in' is not spelled correctly – Loko Apr 21 '15 at 11:18
  • OMG... phpMyAdmin is database???? – Anowar Hossain Apr 21 '15 at 11:19
  • @AnowarCst Yeah phpMyAdmin is the database. It is only for university. – user3545833 Apr 21 '15 at 11:22
  • 1
    Please, [stop using `mysql_*` functions](http://stackoverflow.com/questions/12859942/why-shouldnt-i-use-mysql-functions-in-php). They are no longer maintained and are [officially deprecated](https://wiki.php.net/rfc/mysql_deprecation). Learn about [prepared statements](http://en.wikipedia.org/wiki/Prepared_statement) instead, and use [PDO](http://jayblanchard.net/demystifying_php_pdo.html). – Jay Blanchard Apr 21 '15 at 11:27
  • phpMyAdmin *is not a database* @user3545833. It is an *interface* through which you can connect to databases. Who is teaching these courses? ¯\\_(ツ)_/¯ – Jay Blanchard Apr 21 '15 at 11:28
  • are you sure your database is phpMyAdmin??? I was never listen about this database. I know [phpMyAdmin](http://en.wikipedia.org/wiki/PhpMyAdmin) open source tool . Can you explain me or give me a link?? @user3545833 – Anowar Hossain Apr 21 '15 at 11:28
  • 1
    @JayBlanchard *Choo choo!* - See Wile E. standing in the middle of the track; waiting for "it". *I can see stars*. 2001... – Funk Forty Niner Apr 21 '15 at 11:38

3 Answers3

2

First:

Add the following at the top of you php script:

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

The above will help you understand which lines of your code aren't correct (comment on production mode).

It should be if(isset($_POST['liusername'])) not only isset($_POST['liusername'])

The first part of you code should look like this:

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

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

Second:

If you strip_tags here:

$username = strip_tags($_POST['liusername']);

Why would you use the original $_POST['liusername'] on your query?
Also, you should use mysql_real_escape_string() instead of strip_tags to avoid mysql injections.

The second part of your code should look like this:

$username = mysql_real_escape_string($_POST['liusername']);
$password = mysql_real_escape_string($_POST['lipassword']);

Third:

You're not fetching anything from the DB.
To be able to get any results, like username and password, you first need to fetch the DB.

The third part your code should look like this:

$result = mysql_query("SELECT user_id, user_password FROM user WHERE 
    user_password = '$username' ");
$row = mysql_fetch_assoc($result); // You missed this

if ($row['user_password'] === $_POST['lipassword'] &&
$row['user_id'] === $_POST['liusername'] ){ // it's user_id not user_username

    $_SESSION ['loggedin'] = true;
    $_SESSION ['id'] = $row['user_id'];

}else{

    $_SESSION['loggedin'] = false;
    $_SESSION ['id'] = 0;
}

Conclusion:

Go over you code line by line and check for this type of errors.
I'll let you figure out the rest...

<?php

error_reporting(E_ALL);
ini_set('display_errors', '1');
session_start();
if(isset($_POST['liusername'])) {

    $username = mysql_real_escape_string($_POST['liusername']);
    $password = mysql_real_escape_string($_POST['lipassword']);

    $result = mysql_query("SELECT user_id, user_password FROM user WHERE 
        user_password = '$username' ");
    $row = mysql_fetch_assoc($result); // You missed this

    if ($row['user_password'] === $_POST['lipassword'] &&
     $row['user_id'] === $_POST['liusername'] ){ // it's user_id not user_username

        $_SESSION['loggedin'] = true;
        $_SESSION['id'] = $row['user_id'];

    }else{

        $_SESSION['loggedin'] = false;
        $_SESSION ['id'] = 0;
    }

}

You should spare some time to read this article:
http://www.wikihow.com/Create-a-Secure-Login-Script-in-PHP-and-MySQL

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268
  • **4th** - Storing plain text passwords rather than a hash is totally unsafe. – Funk Forty Niner Apr 21 '15 at 11:35
  • @Fred-ii- step by step... first the user just need some guidance. – Pedro Lobito Apr 21 '15 at 11:36
  • No - not step-by-step in this case @PedroLobito. It is dangerous and should be pointed out. The SQL Injection possibility is dangerous and should be pointed out. The OP thinks phpMyAdmin is *the database* for goodness sakes! – Jay Blanchard Apr 21 '15 at 11:42
  • @Fred-ii- If the "OP thinks phpMyAdmin is the database" do you think we should talk about password encryption now ? – Pedro Lobito Apr 21 '15 at 11:43
  • 1
    @PedroLobito this whole thing is a train wreck to start with. I'm wondering if the OP even knows what to do with the answers given too. Then they stand at saying *it doesn't work....*. Yeah I guess like you say; at this point it's not even important mentioning the fact about their usage of password storage methods lol – Funk Forty Niner Apr 21 '15 at 11:47
  • @Fred-ii- I'm know what you're saying about _it doesn't work._ it's very frustrating... – Pedro Lobito Apr 21 '15 at 11:49
  • 1
    @PedroLobito Yep, been there, got the T-shirt and stopped wearing it lol - Least your answer explains it to the OP which is the type of answer we all like to see ;-) – Funk Forty Niner Apr 21 '15 at 11:51
0
//below is the revised code 


<?php

session_start();

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

    // Clean the code coming from the user
    $username = strip_tags(trim($_POST['liusername']));
    $password = trim($_POST['lipassword']);

//find the record in database that corresponds to this user
    $result = mysql_query("SELECT user_id FROM user WHERE 
user_username = '" . $username . "' AND user_password='" . $password . "'");

//fetch the record
    $row = mysql_fetch_array($result);

//if record count is more than 0 than user's credentials are valid logged
//him in and set the session

    if (mysql_num_rows($result) > 0) {//valid user
        $_SESSION ['loggedin'] = true;
        $_SESSION ['id'] = $row['user_id'];
        echo "Login Successful";
    } else {

        $_SESSION['loggedin'] = false;
        $_SESSION ['id'] = 0;
        echo "Invalid Username password";
    }
}
?>
vivek
  • 32
  • 2
  • 3
    Why should the OP try this? Please add an explanation of what you did and why you did it that way not only for the OP but for future visitors to SO. – Jay Blanchard Apr 21 '15 at 11:29
  • Warning: mysql_fetch_array() expects parameter 1 to be resource, boolean given in C:\wamp\www\Assignment\includes\pagetop.php on line 15 Warning: mysql_num_rows() expects parameter 1 to be resource, boolean given in C:\wamp\www\Assignment\includes\pagetop.php on line 20 – user3545833 Apr 21 '15 at 14:12
  • ^^ are the errors I get when implementing this code – user3545833 Apr 21 '15 at 14:12
  • @user3545833 you did add your DB credentials in there too right? this answer did not include what you're using and would be the reason for the warnings. – Funk Forty Niner Apr 21 '15 at 14:18
  • Its failing because, i think the select query is throwing error , please check your table name and fields name and please include db config file appropriately. – vivek Apr 25 '15 at 06:57
-1

Try with below code i using without sessions login done:

Form.html:-

<form id="form" action='login.php' method='post' enctype="multipart/form=data">
        Username: <input type='text' name='myusername'></br>
        Password: <input type='password' name='mypassword'></br>
        <input type='submit' value='Login'  name="submit">
</form>

Login.php:-

<?php

$host="localhost"; // Host name 
$username="root"; // Mysql username 
$password=""; // Mysql password 
$db_name="Database name"; // Database name 
$tbl_name="Table name "; // Table name 

// Connect to server and select databse.
mysql_connect("$host", "$username", "$password")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form 
$myusername=$_POST['myusername']; 
$mypassword=$_POST['mypassword']; 

// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);
$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result=mysql_query($sql);
$count=mysql_num_rows($result);
if($count==1){
header("location:login_success.php");
}
else {
echo "Wrong Username or Password";
}
?>

login_success.php:-

<html>
<body>
Login Successful
</body>
</html>

this is working perfectly. Hope this helps.

RaMeSh
  • 3,330
  • 2
  • 19
  • 31