• Advertisement
Sign in to follow this  

[web] [PHP] Trouble with my login script

This topic is 4142 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

ive been following the tutorials from http://www.php-mysql-tutorial.com, and im having some trouble with my login script. ive been messing around with it for about 45 minutes with no luck at all. Anyway, here it is:
<?php
// we must never forget to start the session
session_start(); 
$errorMessage = '';
if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) {
   include 'config.php';

   $userId = $_POST['txtUserId'];
   $password = $_POST['txtPassword'];

   // check if the user id and password combination exist in database
   $sql = "SELECT user_id 
           FROM users
           WHERE user_id = '$userId' 
                 AND user_password = PASSWORD('$password')";

   $result = mysql_query($sql) 
             or die('Query failed. ' . mysql_error()); 

   if (mysql_num_rows($result) == 1) {
      // the user id and password match, 
      // set the session
      $_SESSION['db_is_logged_in'] = true;


// after login we move to the main page
header('Location: index.php');
exit;
} else {
$errorMessage = 'Sorry, wrong user id / password';
}
}

?>

<title>Basic Login</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head> 
<body>
<?php
if ($errorMessage != '') {
?>
<p align="center"><?php echo $errorMessage; ?>

<?php } ?> <form method="post" name="frmLogin" id="frmLogin"> <table width="400" border="1" align="center" cellpadding="2" cellspacing="2"> <tr> <td width="150">User Id</td> <td><input name="txtUserId" type="text" id="txtUserId"></td> </tr> <tr> <td width="150">Password</td> <td><input name="txtPassword" type="password" id="txtPassword"></td> </tr> <tr> <td width="150"> </td> <td><input type="submit" name="btnLogin" value="Login"></td> </tr> </table> </form> </body> </html>
The problem im having is that regardless of what I type into the user id/pass feilds, it always says the the pass or id is wrong. I have created a few test accounts in the database, and none of them work. Could someone please tell me whats wrong?

Share this post


Link to post
Share on other sites
Advertisement
1° You have security issues, since anyone could perform SQL injection through that script.
2° Ugly, ugly HTML. It isn't even well-formed.

Now, for the actual debugging, can you please give us the following output:
- The contents of the users table
- The generated and used mysql query
- The data returned by the mysql query

Share this post


Link to post
Share on other sites
Quote:
1° You have security issues, since anyone could perform SQL injection through that script.

2° Ugly, ugly HTML. It isn't even well-formed.


1. I'm simply following the tutorials at this point. I really have no idea how to make it more secure.
2. It was just copied from the tutorial. html I DO know, so I plan to fix that :D

anyway, the 'users' table has two 'collums' (is that what their called?):

user_id and user_password. I currently have two usernames and two passwords. As for your other questions, im not sure what you mean. Could you tell me how I find these things out?

Share this post


Link to post
Share on other sites
Turn this:

// check if the user id and password combination exist in database

$sql = "SELECT user_id, user_password

FROM users

WHERE user_id = '$userId'

AND user_password = PASSWORD('$password')";



$result = mysql_query($sql)

or die('Query failed. ' . mysql_error());



Into this:

// check if the user id and password combination exist in database

$sql = "SELECT user_id

FROM users

WHERE user_id = '$userId'

AND user_password = PASSWORD('$password')";


echo "QUERY:<pre>$sql</pre><br/>";

$result = mysql_query($sql)

or die('Query failed. ' . mysql_error());

while($row = mysql_fetch_assoc($result)) {
echo "<pre>";
print_r ($row);
echo "</pre><br/>";
}


$sql = "SELECT *

FROM users";


echo "QUERY:<pre>$sql</pre><br/>";

$result = mysql_query($sql)

or die('Query failed. ' . mysql_error());

while($row = mysql_fetch_assoc($result)) {
echo "<pre>";
print_r ($row);
echo "</pre><br/>";
}



Correct any syntax errors if I made them unintentionally. Then, do the test again, and show the results here. Don't forget to backup your previous code before changing it.

Share this post


Link to post
Share on other sites
If you're new to this and you want a good auth mechanism I think PEAR is something worth looking into. It takes care of a lot of things for you.

PEAR (http://pear.php.net)
PEAR DB
PEAR Auth

Share this post


Link to post
Share on other sites
Quote:
Original post by ToohrVyk
Turn this:
*** Source Snippet Removed ***

Into this:
*** Source Snippet Removed ***

Correct any syntax errors if I made them unintentionally. Then, do the test again, and show the results here. Don't forget to backup your previous code before changing it.


I still get the same error, but here are the query results:


QUERY:
SELECT user_id, user_password

FROM users

WHERE user_id = 'admin'

AND user_password = PASSWORD('adminpass')

QUERY:
SELECT *

FROM users


Array
(
[user_id] => admin
[user_password] => adminpass
)



Array
(
[user_id] => dog
[user_password] => dogo



And pipeten and mediahack, thank you both for your suggestions.

Share this post


Link to post
Share on other sites
for a login-system, all you have to learn are session-cookies and a tiny bit of mysql.

you'll need at least 2 pages (or three, if you want to display the logged in user).

the first page will have a simple form, with user/password and submit button. i suppose you know to do this :) careful with the name property of each, since you'll use this in the second page. the form is supposed to have it's action pointed at the second page.

now, on the second page, before any line, even before the DTD, write something like this
<?php session_start(); ?>




sessions are a special type of variables that get carried around pages :) like the variables on the index, are also seen by the contact page (for example) - as long as you put the session_start. another interesting thing about them is that the user is just given an id, and all the data linked with that id is stored on the server, so it's much safer to use them to store user data, instead of cookies. on to the second page :)

in the <body> section, do this

<?php
$name=$_POST['username'];
$pass=$_POST['password']
//notice that i used username and password, you have to put between the square brackets the name you used on the form elements in page one (the username and password field)

//you'll need to connect to mysql here
mysql_connect($host,$user,$pass);
//and select your database
mysql_query("USE $dbname");

//replace $host, $user, $pass and $dbname with your database credentials
//now, we're connected, we'll have to check if the password supplied by the user is the right one. what we're doing is asking the database to give us the username that has the user and pass supplied by our visitor.

$n=mysql_query("SELECT user_id FROM users WHERE user_id = '$name' AND user_password = '$pass'");

//we've got in the $n variable the result, but we need to decode it, and convert it into an array. this is how it's done
$result=mysql_fetch_assoc($n);

//now we should check what the database returned. we requested the user_id with the username and password supplied by the user. of course, if they don't exist, the database will return blank

if ($result['user_id']!='') {
$_SESSION['logged_in_user']=$result['user_id'];

//this may not be the safest method, but for understanding a login system, it's ok. at this point, you will want to redirect the user to another page
header("Location: thirdpage.php");

} else {
//insert here the DTD, html and body tags, and somewhere, the "login failed"
//the point of doing the check before the html tag, is because the header (the command we use for redirecting by sending a header) must be sent before any data. you may want to perform additional checks, too
}
?>





on the third page, we will show the logged in user


<?php
session_start();
// put this part before the DTD
?>

<?php
//and this one in the body tag
echo "Hi, ".($_SESSION['logged_in_user'])."! Welcome to our site!<br>";

?>





That's basically it. Of course, with time and by looking over several scripts, you'll see there are better methods of doing so.
Note: i haven't followed the tutorial, but i tried to explain you the way i do it. it's the same idea as in the tutorial.

Share this post


Link to post
Share on other sites
Quote:
Original post by Terradigits
Array
(
[user_id] => admin
[user_password] => adminpass
)


That's what we needed to know. Your table contains the passwords themselves, but your SELECT operation is looking for the password hashes instead. Two possible solutions:
1- Remove the PASSWORD() call from the SELECT statement, so you don't look for the password hash but for the actual password instead.
2- Add a PASSWORD() call when inserting into the table, so it stores the hash.

mySQL advises you to use the first one, or use a function other than PASSWORD (such as explicitly naming your hash method).

Other than that, mysql_escape_string is deprecate. Use mysql_real_escape_string instead.

Share this post


Link to post
Share on other sites
Thank you both ToohrVyk and izua for your help. Hopefully I can get this working now :D

EDIT: ive tried what both ToohrVyk and izua have told me, but im getting an "unexpected T_VARIABLE" error for each. ill mess around more and see if I can fic it myself. If not, ill be back here to post :)

EDIT2: Here is my current code, all on one page


<?php
// we must never forget to start the session
session_start();
$errorMessage = '';
if (isset($_POST['txtUserId']) && isset($_POST['txtPassword'])) {
include 'config.php';


$userId = $_POST['txtUserId'];
$password = $_POST['txtPassword'];

// check if the user id and password combination exist in database
$sql = "SELECT user_id
FROM users
WHERE user_id = '$userId'
AND user_password = '$password';

$result = $result=mysql_fetch_assoc($n);

if ($result['user_id']!=') {

// the user id and password match,
// set the session
$_SESSION['db_is_logged_in'] = true;

// after login we move to the main page
header('Location: index.php');
exit;
} else {
$errorMessage = 'Sorry, wrong user id / password';
}

}
?>

<title></title>

<form method=post action=frmlogin>
Username <input type=text name=username>

Password <input type=text name=password>

<input type=submit>
</form>
</body>
</html>


The line that is giving me trouble is not code-commented. it is if ($result['user_id']!=') {. the error is Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING on line 20

[Edited by - Terradigits on October 15, 2006 9:15:05 AM]

Share this post


Link to post
Share on other sites
Hi,

I won't help you with your code, but here are 2 quite good tutorials about creating a login system in PHP:
PHP Login Script with Remember Me Feature
PHP Login System with Admin Features
Both are written by the same author. The second one is just more advanced version of the first one. The code is rather clean and simple.

Regarding SQL injection - it's not something you should be worrying about at the very beginning, but later you should really take care of that:
SQL Injection Attacks by Example
">A movie!

I don't want to discourage you from learning php, but just take a look at Ruby on Rails [smile]

Share this post


Link to post
Share on other sites
as Sander said, fix this on line 4


$errorMessage = ';




into this:


$errorMessage = ''';




and this one (line 21, in the code posted above)


if ($result['user_id']!=') {




into this


if ($result['user_id']!=''') {




Hope it helps. you should also get some editor with syntax highlighting. i'm not recommending dreamweaver, if you don't want to make a living out of web-dev, but there are a lot of free editors out there. They'll help you notice this kind of mistakes, by showing you what's between a string (and you'll have to see what's a string, and what should be code).

best of all,
izua

Share this post


Link to post
Share on other sites
Thank you everyone for your help. ill try to fix up my code tommorow and gret back to you guys with any questions I may have.

Share this post


Link to post
Share on other sites
Its me again :D. ive finally had time to get back to this. ive updated my code with your suggestions, but im still getting an error:

Parse error: syntax error, unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING in [login.php]

Share this post


Link to post
Share on other sites
Terradigits, PHP should've also included the offending line number with the error. Could you post that line of code along with the preceding line and the one that follows?

Share this post


Link to post
Share on other sites
sorry, didnt realize I cut that out. The line number is 20, here is the code:


// check if the user id and password combination exist in database
$sql = "SELECT user_id
FROM users
WHERE user_id = '$userId'
AND user_password = '$password';

$result = $result=mysql_fetch_assoc($n); //LINE 20


if ($result['user_id']!=') {

Share this post


Link to post
Share on other sites
here :)


$result = $result=mysql_fetch_assoc($n); //LINE 20



replace this one with:


$result = mysql_fetch_assoc($n); //LINE 20



i'm not sure if you can do this type of associations in php. it might be possible, though. but you just want to get the result from mysql into a variable :)

izua

Share this post


Link to post
Share on other sites
I hate it when I make stupid typos like that :). I really do need to get an editor...

EDIT: hmm I still get the same error

Share this post


Link to post
Share on other sites
Actually, PHP will should parse that without error believe it or not. What I don't understand is what the $n variable is representing...and you dropped the call to mysql_query. You'll need that to get a valid mysql resource which you would then pass to mysql_fetch_assoc().

The error you're getting is caused by not properly closing the string containing the SQL with a double quote.

Here's the fixed version of the code snippet you provided:

// check if the user id and password combination exist in database

$sql = "SELECT user_id

FROM users

WHERE user_id = '$userId'

AND user_password = '$password'"; // closed string w/ double quote

$result = mysql_query($result) or die(mysql_error); // get mysql result resource

$row = mysql_fetch_assoc($result); //LINE 20

if (!empty($row['user_id'])) {



But in all honesty, this seems like your first attempt at PHP and there's many parts of the code which could throw errors and many parts which could be optimized and secured better. I recommend starting a bit smaller like getting through some hello worlds and learning how form data is accessed, etc. Just experiment and get the basics down so that you always understand exactly what's going on.

Then move on to putting it together as a useful application. Also be sure to consult the PHP Manual to learn about all the useful functions PHP offers.

As previously mentioned, a syntax highlighting editer is indispensible. Google "PHP Designer" for the one I use. (it's a free download)

Hopefully this provides some insight...good luck with everything.

Share this post


Link to post
Share on other sites
hm, haven't noticed that error.

my first attempt in php was a very simple guestbook. i just put entries in it manually, and i attempted a few days to make a script to show them.

the next thing i tried, was understanding how to make visitors add stuff into it. i kind of understood after this step what's "the thing" with PHP (though i had some previous visual basic knowledge), and i tried making projects with several difficulty after this one.

if you really can't understand how it works, drop me a pm, and i'll make a working example with comments

izua

Share this post


Link to post
Share on other sites
I think I understand how it works, but now im getting more run-time problems. I'm actually going to rewrite it from scratch using a different tutorial and see if that helps. Thank you for your offer they. I may still PM you if I run into more trouble.

Share this post


Link to post
Share on other sites
Sign in to follow this  

  • Advertisement