The Web Design Group

... Making the Web accessible to all.

Welcome Guest ( Log In | Register )

3 Pages V  1 2 3 >  
Reply to this topicStart new topic
> PHP Login Troubles Using PDO
SBH
post Aug 11 2015, 05:05 AM
Post #1


Member
***

Group: Members
Posts: 82
Joined: 6-February 15
Member No.: 22,158



I searched & went through a few threads on PHP login scripts. Since I could not find a way out, I am posting my code & requesting for help, as I'm not sure why the login doesn't happen. Thanks.

'Login Failed' is the message I persistently get. You can see in the bottom if-else condition within the Try Loop

CODE

$usrname = filter_var($_POST['usrname'], FILTER_SANITIZE_STRING);
    $passwrd = filter_var($_POST['passwrd'], FILTER_SANITIZE_STRING);

    /*** now we can encrypt the password ***/
    $passwrd = sha1( $passwrd );
    
    /*** connect to database ***/
    /*** mysql hostname ***/
    $mysql_hostname = 'localhost';

    /*** mysql username ***/
    $mysql_username = ‘XXXXX’;

    /*** mysql password ***/
    $mysql_password = ‘YYYYY’;

    /*** database name ***/
    $mysql_dbname = ‘ZZZZZ’;

    try
    {
        $dbh = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname",
                $mysql_username, $mysql_password);
        /*** $message = a message saying we have connected ***/

        /*** set the error mode to excptions ***/
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        /*** prepare the select statement ***/
        $stmt = $dbh->prepare("SELECT username, password FROM U_Authentications
    *              WHERE username = :usrname AND password = :passwrd");

        /*** bind the parameters ***/
        $stmt->bindParam(':usrname', $usrname, PDO::PARAM_STR);
        $stmt->bindParam(':passwrd', $passwrd, PDO::PARAM_STR, 40);

        /*** execute the prepared statement ***/
        $stmt->execute();

        /*** check for a result ***/
        $user_id = $stmt->fetchColumn();

        /*** if we have no result then fail boat ***/
        if($user_id == false)
        {
                $message = 'Login Failed';
        }
        /*** if we do have a result, all is well ***/
        else
        {
                /*** set the session user_id variable ***/
                $_SESSION['user_id'] = $user_id;

                /*** tell the user we are logged in ***/
                $message = 'You are now logged in';
        }


    }
    
    catch(Exception $e)
    {
        /*** if we are here, something has gone wrong with the database ***/
        $message = 'We are unable to process your request. Please try again later"';
    }
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
SBH
post Aug 12 2015, 01:58 AM
Post #2


Member
***

Group: Members
Posts: 82
Joined: 6-February 15
Member No.: 22,158



Boy, over a day & no response. Wonder why? sad.gif sad.gif sad.gif
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post Aug 12 2015, 05:38 AM
Post #3


.
********

Group: WDG Moderators
Posts: 7,947
Joined: 10-August 06
Member No.: 7



QUOTE(SBH @ Aug 11 2015, 12:05 PM) *

'Login Failed' is the message I persistently get.

I don't know PDO, but what do you get if f you print out the DB responses at various stages?

I'm no good at MySQL either, but should this * character be there:

QUOTE
CODE
        $stmt = $dbh->prepare("SELECT username, password FROM U_Authentications
    *              WHERE username = :usrname AND password = :passwrd");

? unsure.gif
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
CharlesEF
post Aug 12 2015, 06:03 AM
Post #4


Programming Fanatic
********

Group: Members
Posts: 1,549
Joined: 27-April 13
From: Edinburg, Texas
Member No.: 19,088



In addition to what Christian said about the * character, I see some funny single quote characters also, like:
CODE
/*** mysql username ***/
$mysql_username = ‘XXXXX’;

/*** mysql password ***/
$mysql_password = ‘YYYYY’;

/*** database name ***/
$mysql_dbname = ‘ZZZZZ’;

Seems you have both types of single quotes spread around. You should change them to normal single quotes.

Also, your try block looks funny. A try/catch block catches an error (like connecting to your database) but you seem to be trying to catch all errors under the sun.

This post has been edited by CharlesEF: Aug 12 2015, 06:05 AM
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
SBH
post Aug 12 2015, 06:06 AM
Post #5


Member
***

Group: Members
Posts: 82
Joined: 6-February 15
Member No.: 22,158



Ok lemme reply to both of you on by one.

First @Christian J - Yes, Login Failed is what I get, despite I using the username/password combo, which I've populated in the mysql table. As for the *, you can ignore. It's a copy paste mistake on my part.

@CharlesEF - The funny try block, as you call them, + quotes are stuff that I copy-pasted from a website as is. Will try to change that & see if that helps in any way.

This post has been edited by SBH: Aug 12 2015, 06:10 AM
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
CharlesEF
post Aug 12 2015, 06:13 AM
Post #6


Programming Fanatic
********

Group: Members
Posts: 1,549
Joined: 27-April 13
From: Edinburg, Texas
Member No.: 19,088



QUOTE(SBH @ Aug 12 2015, 06:06 AM) *

@CharlesEF - The funny try block, as you call them, + quotes are stuff that I copy-pasted from a website as is. Will try to change that & see if that helps in any way.

When I leave the funny quotes in this is the error message I get:
CODE
[12-Aug-2015 06:11:13 America/Chicago] PHP Notice:  Use of undefined constant ‘XXXXX’ - assumed '‘XXXXX’' in E:\Intranet\CEF, Inc\test\login.php on line 16
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
SBH
post Aug 12 2015, 06:20 AM
Post #7


Member
***

Group: Members
Posts: 82
Joined: 6-February 15
Member No.: 22,158



QUOTE(CharlesEF @ Aug 12 2015, 06:13 AM) *

QUOTE(SBH @ Aug 12 2015, 06:06 AM) *

@CharlesEF - The funny try block, as you call them, + quotes are stuff that I copy-pasted from a website as is. Will try to change that & see if that helps in any way.

When I leave the funny quotes in this is the error message I get:
CODE
[12-Aug-2015 06:11:13 America/Chicago] PHP Notice:  Use of undefined constant ‘XXXXX’ - assumed '‘XXXXX’' in E:\Intranet\CEF, Inc\test\login.php on line 16


Well that's coz I masked the names of the [DB] username, [DB] password & the DBNAME itself to something fictitious. If you'd be able to replace that with corresponding parameters on your end, that'd work I guess (or not work, helping you replicate the error)
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
CharlesEF
post Aug 12 2015, 06:24 AM
Post #8


Programming Fanatic
********

Group: Members
Posts: 1,549
Joined: 27-April 13
From: Edinburg, Texas
Member No.: 19,088



QUOTE(SBH @ Aug 12 2015, 06:20 AM) *

QUOTE(CharlesEF @ Aug 12 2015, 06:13 AM) *

QUOTE(SBH @ Aug 12 2015, 06:06 AM) *

@CharlesEF - The funny try block, as you call them, + quotes are stuff that I copy-pasted from a website as is. Will try to change that & see if that helps in any way.

When I leave the funny quotes in this is the error message I get:
CODE
[12-Aug-2015 06:11:13 America/Chicago] PHP Notice:  Use of undefined constant ‘XXXXX’ - assumed '‘XXXXX’' in E:\Intranet\CEF, Inc\test\login.php on line 16


Well that's coz I masked the names of the [DB] username, [DB] password & the DBNAME itself to something fictitious. If you'd be able to replace that with corresponding parameters on your end, that'd work I guess (or not work, helping you replicate the error)

What I was trying to show you was the fact that using those funny quotes is part of the error message I was showing you. The value of $mysql_username is now ‘XXXXX’, including the funny quotes.

This post has been edited by CharlesEF: Aug 12 2015, 06:26 AM
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
Christian J
post Aug 12 2015, 08:40 AM
Post #9


.
********

Group: WDG Moderators
Posts: 7,947
Joined: 10-August 06
Member No.: 7



QUOTE(SBH @ Aug 12 2015, 01:06 PM) *

First @Christian J - Yes, Login Failed is what I get,

That's because the $user_id variable is false:

CODE

        if($user_id == false)
        {
                $message = 'Login Failed';
        }

...so you could try to find where that fails, e.g. by printing the SQL query result (assuming that there's no error in the query, DB connection or POST data). Check the code output systematically from the beginning.

Also make sure that the username and password records in the DB were filtered and encrypted the same way as when the user submits them in the form. For example, if the password is "foo<p>bar", the filter will change it to "foobar".

BTW, the PHP manual advises against using sha1() for password encryption, see http://php.net/manual/en/faq.passwords.php...swords.fasthash


User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
SBH
post Aug 12 2015, 09:09 AM
Post #10


Member
***

Group: Members
Posts: 82
Joined: 6-February 15
Member No.: 22,158



QUOTE(CharlesEF @ Aug 12 2015, 06:24 AM) *

QUOTE(SBH @ Aug 12 2015, 06:20 AM) *

QUOTE(CharlesEF @ Aug 12 2015, 06:13 AM) *

QUOTE(SBH @ Aug 12 2015, 06:06 AM) *

@CharlesEF - The funny try block, as you call them, + quotes are stuff that I copy-pasted from a website as is. Will try to change that & see if that helps in any way.

When I leave the funny quotes in this is the error message I get:
CODE
[12-Aug-2015 06:11:13 America/Chicago] PHP Notice:  Use of undefined constant ‘XXXXX’ - assumed '‘XXXXX’' in E:\Intranet\CEF, Inc\test\login.php on line 16


Well that's coz I masked the names of the [DB] username, [DB] password & the DBNAME itself to something fictitious. If you'd be able to replace that with corresponding parameters on your end, that'd work I guess (or not work, helping you replicate the error)

What I was trying to show you was the fact that using those funny quotes is part of the error message I was showing you. The value of $mysql_username is now ‘XXXXX’, including the funny quotes.

Oh Ok ... Got you. Will change that & see how it works. Thanks.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
SBH
post Aug 12 2015, 09:14 AM
Post #11


Member
***

Group: Members
Posts: 82
Joined: 6-February 15
Member No.: 22,158



QUOTE(Christian J @ Aug 12 2015, 08:40 AM) *

QUOTE(SBH @ Aug 12 2015, 01:06 PM) *

First @Christian J - Yes, Login Failed is what I get,

That's because the $user_id variable is false:

CODE

        if($user_id == false)
        {
                $message = 'Login Failed';
        }

...so you could try to find where that fails, e.g. by printing the SQL query result (assuming that there's no error in the query, DB connection or POST data). Check the code output systematically from the beginning.

Also make sure that the username and password records in the DB were filtered and encrypted the same way as when the user submits them in the form. For example, if the password is "foo<p>bar", the filter will change it to "foobar".

BTW, the PHP manual advises against using sha1() for password encryption, see http://php.net/manual/en/faq.passwords.php...swords.fasthash

Well yes, the user_id is false & despite printing/echo-ing the SQL results, I am unable to find anything. Basically, should I use anything instead of a fetchColumn() or a fetch() function? Guess, they fetch the next column/row, both of which may be empty, thus setting user_id to false?

Also, my password (hitherto only for test purpose) is a simple combo of alphabets (no numerals, let alone any special characters).

Finally, will look into the encryption recommendation by PHP. Thanks for sharing the link
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
masonh928
post Aug 13 2015, 08:32 PM
Post #12


Serious Coder
*****

Group: Members
Posts: 250
Joined: 17-August 13
From: Indiana
Member No.: 19,570



I use PDO, so lemme see what I can do…
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
masonh928
post Aug 13 2015, 08:38 PM
Post #13


Serious Coder
*****

Group: Members
Posts: 250
Joined: 17-August 13
From: Indiana
Member No.: 19,570



Ok first off let me say, please do NOT use sha1. Use hash pass library or something like PHP's native password hasher.

password_hash() it is so easy to use, read more about it on PHP.net…

Anyways, don't use bindParams() for PDO either. Use bindValue() instead, it works same, but used in different things…

Also I believe you should use, $stmt->fetchAll() instead… This is 100% better, then use count($user_id)…

CODE

if(count($user_id) < 1){
echo("Password wrong or whatever you want");
}


I will give a more detailed response tmrw.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
SBH
post Aug 14 2015, 06:26 AM
Post #14


Member
***

Group: Members
Posts: 82
Joined: 6-February 15
Member No.: 22,158



QUOTE(masonh928 @ Aug 13 2015, 08:38 PM) *

Ok first off let me say, please do NOT use sha1. Use hash pass library or something like PHP's native password hasher.

password_hash() it is so easy to use, read more about it on PHP.net…

Anyways, don't use bindParams() for PDO either. Use bindValue() instead, it works same, but used in different things…

Also I believe you should use, $stmt->fetchAll() instead… This is 100% better, then use count($user_id)…

CODE

if(count($user_id) < 1){
echo("Password wrong or whatever you want");
}


I will give a more detailed response tmrw.

@masonh928 - Thanks a ton. Will take your advice as is. Also can't tell how much I'm waiting with bated breath for your detailed response. Thanks a ton again.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
masonh928
post Aug 14 2015, 07:14 PM
Post #15


Serious Coder
*****

Group: Members
Posts: 250
Joined: 17-August 13
From: Indiana
Member No.: 19,570



I think this may be better:

CODE


$usrname = filter_var($_POST['usrname'], FILTER_SANITIZE_STRING);
    $passwrd = filter_var($_POST['passwrd'], FILTER_SANITIZE_STRING);

    /*** now we can encrypt the password ***/
    $passwrd = password_hash($passwrd, PASSWORD_DEFAULT);
    
    /*** connect to database ***/
    /*** mysql hostname ***/
    $mysql_hostname = 'localhost';

    /*** mysql username ***/
    $mysql_username = ‘XXXXX’;

    /*** mysql password ***/
    $mysql_password = ‘YYYYY’;

    /*** database name ***/
    $mysql_dbname = ‘ZZZZZ’;

    try
    {
        $dbh = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname",
                $mysql_username, $mysql_password);
        /*** $message = a message saying we have connected ***/

        /*** set the error mode to excptions ***/
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        /*** prepare the select statement ***/
        $stmt = $dbh->prepare("SELECT * FROM U_Authentications WHERE username = :usrname AND password = :passwrd");

        /*** bind the parameters ***/
        $stmt->bindValue(":usrname", $usrname);
        $stmt->bindValue(":passwrd", $passwrd);

        /*** execute the prepared statement ***/
        $stmt->execute();

        /*** check for a result ***/
        $user_id = $stmt->fetchAll();

        /*** if we have no result then fail boat ***/
        if(count($user_id) < 1){
                $message = 'Login Failed';
        } else{
                /*** set the session user_id variable ***/
                $_SESSION['user_id'] = $user_id;

                /*** tell the user we are logged in ***/
                $message = 'You are now logged in';
        }

    } catch(Exception $e){
        /*** if we are here, something has gone wrong with the database ***/
        $message = 'We are unable to process your request. Please try again later';
       echo($message);
       echo("Err:" . $e->getMessage());
    }


This post has been edited by masonh928: Aug 14 2015, 07:16 PM
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
masonh928
post Aug 14 2015, 07:16 PM
Post #16


Serious Coder
*****

Group: Members
Posts: 250
Joined: 17-August 13
From: Indiana
Member No.: 19,570



I may have missed something, if so please tell me...
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
CharlesEF
post Aug 14 2015, 07:36 PM
Post #17


Programming Fanatic
********

Group: Members
Posts: 1,549
Joined: 27-April 13
From: Edinburg, Texas
Member No.: 19,088



QUOTE(masonh928 @ Aug 14 2015, 07:16 PM) *

I may have missed something, if so please tell me...
Your code keeps the same problem he had before, the smart quotes (I call them funny quotes).
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
masonh928
post Aug 14 2015, 10:12 PM
Post #18


Serious Coder
*****

Group: Members
Posts: 250
Joined: 17-August 13
From: Indiana
Member No.: 19,570



what do you mean? funny quotes?
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
CharlesEF
post Aug 14 2015, 10:19 PM
Post #19


Programming Fanatic
********

Group: Members
Posts: 1,549
Joined: 27-April 13
From: Edinburg, Texas
Member No.: 19,088



QUOTE(masonh928 @ Aug 14 2015, 10:12 PM) *

what do you mean? funny quotes?
I mean these vaiables:
CODE
/*** mysql username ***/
$mysql_username = ‘XXXXX’;

/*** mysql password ***/
$mysql_password = ‘YYYYY’;

/*** database name ***/
$mysql_dbname = ‘ZZZZZ’;
The smart quotes were the reason this script did not work in the first place. They need to be changed to normal single or double quotes.
User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post
SBH
post Aug 15 2015, 12:32 AM
Post #20


Member
***

Group: Members
Posts: 82
Joined: 6-February 15
Member No.: 22,158



Ok guys, am catching up on this thread now.

First things, @masonh928 - made changes suggested by you. I see an empty screen - and despite a plethora of echo statements, none of them are showing on the screen. Earlier it used to say "Login Failed" - now it says nothing (not even the successful msg - "You're logged on")

As for @CharlesEF, I've replaced the 'funny quotes' with normal double quotes. What more can I do?

Well, for starters, here's the whole PHP code (I realize I shared only a part - let me know if this merits any changes).

CODE

<?php

/* Login using PDO
*/

/*** begin our session ***/
session_start();

/*** check if the users is already logged in ***/
if(isset( $_SESSION['user_id'] ))
{
    $message = 'User is already logged in';
}
/*** check that both the username, password have been submitted ***/
if(!isset( $_POST['usrname'], $_POST['passwrd']))
{
    $message = 'Please enter a valid username and password';
}
/*** check the username is the correct length ***/
elseif (strlen( $_POST['usrname']) > 20 || strlen($_POST['usrname']) < 4)
{
    $message = 'Incorrect Length for Username';
}
/*** check the password is the correct length ***/
elseif (strlen( $_POST['passwrd']) > 20 || strlen($_POST['passwrd']) < 4)
{
    $message = 'Incorrect Length for Password';
}
/*** check the username has only alpha numeric characters ***/
elseif (ctype_alnum($_POST['usrname']) != true)
{
    /*** if there is no match ***/
    $message = "Username must be alpha numeric";
}
/*** check the password has only alpha numeric characters ***/
elseif (ctype_alnum($_POST['passwrd']) != true)
{
        /*** if there is no match ***/
        $message = "Password must be alpha numeric";
}
else
{
    /*** if we are here the data is valid and we can insert it into database ***/
    $usrname = filter_var($_POST['usrname'], FILTER_SANITIZE_STRING);
    $passwrd = filter_var($_POST['passwrd'], FILTER_SANITIZE_STRING);

    /*** now we can encrypt the password ***/
    $passwrd = password_hash($passwrd, PASSWORD_DEFAULT);
    
    /*** connect to database ***/
    /*** mysql hostname ***/
    $mysql_hostname = "localhost";

    /*** mysql username ***/
    $mysql_username = "XXXXX";

    /*** mysql password ***/
    $mysql_password = "YYYYY";

    /*** database name ***/
    $mysql_dbname = "ZZZZZ";

    try
    {
        $dbh = new PDO("mysql:host=$mysql_hostname;dbname=$mysql_dbname",
                $mysql_username, $mysql_password);
        /*** $message = a message saying we have connected ***/

        /*** set the error mode to excptions ***/
        $dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

        /*** prepare the select statement ***/
        $stmt = $dbh->prepare("SELECT username, password FROM U_Authentications
                   WHERE username = :usrname AND password = :passwrd");

        /*** bind the parameters ***/
        $stmt->bindValue(':usrname', $usrname, PDO::PARAM_STR);
        $stmt->bindValue(':passwrd', $passwrd, PDO::PARAM_STR, 40);

        /*** execute the prepared statement ***/
        $stmt->execute();

        /*** check for a result ***/
    /*    $user_id = $stmt->fetchColumn();*/
        $user_id = $stmt->fetchAll();
        print("User Id = $user_id\n");

        /*** if we have no result then fail boat ***/
        if(count($user_id) < 1)
        {
                $message = 'Login Failed';
        }
        /*** if we do have a result, all is well ***/
        else
        {
                /*** set the session user_id variable ***/
                $_SESSION['user_id'] = $user_id;

                /*** tell the user we are logged in ***/
                $message = 'You are now logged in';
                echo ($message);
        }


    }
    
    catch(Exception $e)
    {
        /*** if we are here, something has gone wrong with the database ***/
        $message = 'We are unable to process your request. Please try again later';
        echo ($message);
        echo ("Err: . $e->getMessage()");
    }
}
?>

<html>
<head>
<title>Welcome to Project 50</title>
</head>
<body>
<p><?php    echo $message;
            echo $user_id;
            echo $usrname;
            echo $passwrd;
    ?>
</body>
</html>


User is offlinePM
Go to the top of the page
Toggle Multi-post QuotingQuote Post

3 Pages V  1 2 3 >
Reply to this topicStart new topic
1 User(s) are reading this topic (1 Guests and 0 Anonymous Users)
0 Members:

 



- Lo-Fi Version Time is now: 20th November 2018 - 01:12 AM