0

I am trying to let a user log in. If the password and username is wrong, I want a popup to appear alerting the user on the error. When they close the alert, it goes back to index.php which is back to login screen.

But when it is wrong password/username, ends up going back to index.php without any popup messages first. My browser setting is not blocking any popups. Can I know what I'm doing wrong please.

<?php
    if($login == true){
        //Do login process
        //this portion works as long as correct username and password
    }
    else{
        echo '<script language="javascript">alert("Please enter valid username and password");</script>';
        header("location:index.php");
    }
?>


//login.php

<?php
    $username = "exampleuser";
    $password = "examplepass";
    $host = "localhost";

    $dbHandle = mysql_connect($host, $username, $password) or die("Could not connect to database");

    $selected = mysql_select_db("database_name", $dbHandle);

    $myUserName = $_POST['user'];
    $myPassword = $_POST['pass'];

    if(ctype_alnum($myUserName) && ctype_alnum($myPassword)){
        $query1 = "SELECT * FROM users WHERE username='$myUserName'";

        $result1 = mysql_query($query1);
        $count1 = mysql_num_rows($result1);

        if($count1 == 1){
            $query2 = "SELECT password FROM users WHERE username='$myUserName'";
            $result2 = mysql_query($query2);

            $row = mysql_fetch_array($result2, MYSQL_ASSOC);
            $pass = $row['password'];

            if(password_verify($myPassword, $pass)){
                $seconds = 120 + time();
                setcookie(loggedIn, date("F js - g:i a"), $seconds);
                header("location:mysite.php");
            }
            else{
                echo '<script language="javascript">
                        alert("Please enter valid username and password");
                        window.location.href = "http://index.php";
                    </script>';
                die();
            }
        }
        else{
                echo '<script language="javascript">
                        alert("Please enter valid username and password");
                        window.location.href = "http://index.php";
                    </script>';
                die();
        }
    }
    else{
        echo '<script language="javascript">
                alert("Please enter valid username and password");
                window.location.href = "http://index.php";
            </script>';
        die();
    }
?>
Trevor_zam
  • 592
  • 2
  • 7
  • 21
  • PHP does not stop after the `echo` has been executed. It continues to tell the browser to move to `index.php`, because all of that happens on the server, not in the user's browser. – Till Helge Oct 06 '15 at 16:48
  • @TillHelge If I totally remove the header(), doesnt work either. I end up seeing a blank page instead of going back to index.php – Trevor_zam Oct 06 '15 at 16:56

1 Answers1

1

If you send headers to php it goes directly on index.php after the page goes in your condition.

If you try this code:

    <?php
if($login == true){
    //Do login process
    //this portion works as long as correct username and password
}
else{
    echo '<script language="javascript">
        alert("Please enter valid username and password");
        window.location.href = "http://index.php";
</script>';
die();
}

you will see that your code is correct. You need to track an event on popup closing to redirect to index.php via ajax or via http redirect.

EDIT 1:

Here you have a complete page with pdo. This is not the best way to do the job but it works. As you will see in the comments you have to avoid xss attacks and you should change database structure saving password hashed and salt to hide the users' clear password.

Here's the code.

<?php
//login.php
//connection via PDO
try{
    $pdo = new PDO ('mysql:host=localhost; dbname=database_name', 'exampleuser' , 'examplepass', array(PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES utf8"));
    //alert errors and warnings
    $pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
}catch(PDOException $e){
    exit('Database Error.');
}

//prepared statements sanitize input binding parameters, for you but you can use some libraries to prevent sql injection
$myUserName = trim(filter_var($_POST['user'], FILTER_SANITIZE_STRING));;
$myPassword = trim(filter_var($_POST['pass'], FILTER_SANITIZE_STRING));;

if(!empty($myUserName) && ctype_alnum($myUserName) && !empty($myPassword) && ctype_alnum($myPassword)){
    $query1 = $pdo->prepare("SELECT password FROM users WHERE username = :username_param");
    //bind parameter avoiding principal injection (pdo does not cover xss attacks, avoid it with other methods)
    $query1->bindParam("username_param", $myUserName);
    $result = $query1->fetch();
    // or you can do $result = $query1->fetchColumn(); to get directly string instead of array

    if($result['password']){
        //you should use password_verify() if you have an hash stored in database, you should not save password in database.
        //please google about best practice storing password, it's full of beautiful guides

        //bad practice but will do the work
        if($myPassword == $result){
            $seconds = 120 + time();
            setcookie('loggedIn', date("F js - g:i a"), $seconds);
            header("location:mysite.php");
        }else{
            printAlert("Password incorrect");
        }
    }else{
        printAlert("Username not valid");
    }
}
else{
    printAlert("Invalid data");

}

function printAlert($text){
    echo "<script language='javascript'>
                alert('$text');
                window.location.href = 'http://index.php';
            </script>";
    die();
}
?>
SBO
  • 623
  • 2
  • 8
  • 22
  • even if I remove the header(), it still doesn't work. I end up on a blank page. Can you give me a rough example please. – Trevor_zam Oct 06 '15 at 16:57
  • Sure, i updated the code. Simply: The code after alert is executed after popup closing. A clientside redirect is called via javascript. A serverside die() function is called to prevent disabling javascript hack to continue executing php script. Now, if you want a redirect by php header i need to make a full coding on your full script page, but i think this is what you are looking for. – SBO Oct 06 '15 at 17:09
  • I get what you mean. But for some reason the popup is not appearing. The login is occurring at index.php. When login button is clicked, it moves to process the information at login.php. When correct, it moves to mysite.php to display the protected info. With the above code, when trying with wrong password, it moves to login.php and stays there with no pop-up and displaying just a white page. The above code is written under login.php file. – Trevor_zam Oct 06 '15 at 17:20
  • I need to see login.php code. look at html code in login.php and see if the alert code is printed – SBO Oct 06 '15 at 17:22
  • I've added the login.php code to the question. – Trevor_zam Oct 06 '15 at 17:28
  • Uhm.. i need some time to rewrite your page. You are using mysql_connect functions, they're deprecated since a few years. Please read about PDO. If you wannna keep mysql_* functions i think you are on the wrong way. If you want i can write your code in PHP 5+. Let me know! – SBO Oct 06 '15 at 19:52
  • PHP 5+ is fine. Thank you. – Trevor_zam Oct 06 '15 at 20:09
  • I added code, it works on my server. Let me know if you are ok with that. Please read about pdo with binding parameter and let mysql_functions to the history, they're deprecated because of weak security. – SBO Oct 07 '15 at 09:10
  • Tnks it works. You mentioned using cookies is bad practice? What would be a better way? – Trevor_zam Oct 07 '15 at 10:15
  • No, bad practice is verifying $myPassword == $result, you should not save password to database but you should save encrypted password and salt to verify equal by a password_hash() function. But this is another question, you can find a lot of best practice googling. Please accept answer if it's what you need so the discussion is closed. Bye! – SBO Oct 07 '15 at 14:50