Jump to content
  • Advertisement
Sign in to follow this  
Terradigits

[web] [PHP] Trouble with my login script

This topic is 4315 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
Sign in to follow this  

  • Advertisement
×

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!