...

View Full Version : Login Script Error



Temper
01-24-2004, 11:55 PM
Okay, I'm having troubles with a login script, and I have no clue what's going wrong. The problem lies in the session that's created, because it logs me in fine, but I don't stay logged in.

This is the index.php file. htmlfns.php and all the functions in this file is just the html source, my layout etc. It has nothing to do with the script. leftcon.php is where the login script actually is.

index.php contents:


<?
session_start();
include ("inc/htmlfns.php");
do_html_head();
include("inc/leftcon.php");
do_html_middle();
?>

<!-- MAIN CONTENT HERE -->


Blahblahblah

<!-- END MAIN CONTENT -->
<? do_html_footer(); ?>


leftcon.php contents:


<?
session_start();
$db = mysql_connect ("localhost", "*****", "*****") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("*****");


$username = $_POST['username'];
$password = $_POST['password'];

if ((!$username) || (!$password)) {
?><center><form name=login method=post action="<? $php_self ?>">
<? echo '<center>You are not logged in</center>
Username: <input type=text name=username class="small" size="16">
Password: <input type=password name=password class="small" size="16">
<center><input type=submit value=Login></center>
<center>Click here to register</center>
</form></center>';
}
else {


$query = "SELECT * FROM user WHERE uname = '$username'";
$result = mysql_query($query, $db) or die(mysql_error());
$numRows = mysql_num_rows($result);
for ($count = 0; $count < $numRows; $count++) {
$resultArray = mysql_fetch_array($result);
}

$uname = $resultArray["uname"];
$pword = $resultArray["pword"];

if (($username == $uname) && ($password == $pword)) {
session_start();
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;

echo "user is $uname, and password is $pword
<br> <a href=\"?action=logout\" >Log Out</a>";
}
else echo "nope";
}

if ($action == "logout") {
session_unregister("username");
session_unregister("password");
}
?>

sitami
01-25-2004, 12:35 AM
try exiting the script ... ..

echo "user is $uname, and password is $pword
<br> <a href=\"?action=logout\" >Log Out</a>";
}
else echo "nope";
exit;
}

if ($action == "logout") {
session_unregister("username");
session_unregister("password");
}


seems to me the script is registering the session vars & then presumimg logout is true and teh unregistering them,

by exiting the script it should ignore logout until it is definatly true

try it and see

hope it helps

sitami
01-25-2004, 12:38 AM
i also notice you have session_start() twice on the page... should only be on the page once at the very top before any code is used at all


eg
<?php
session_start();?>
<?php

my code here ;

?>
<?php include('footer.php');?>

hope that helps too :)

sitami
01-25-2004, 12:52 AM
also ....

replace
<form name=login method=post action="<? $php_self ?>">

with
<form name=login method=post action="<? echo $_SERVER['PHP_SELF']; ?>">

not sure if you have defined $php_self as $_SERVER['PHP_SELF'] ; but thought id ost it and find out :)

raf
01-25-2004, 12:55 AM
Try canging the names of the sessionvariabes.

so change
$_SESSION['username'] = $username;

into
$_SESSION['sesusername']
or so.

I've noticed at some accounts of mine that having the same variablenames (although in different collections) creates problems, so i made it a codingpractice to always have unique variablenames, even across collections.


Also:
- you don't need the second session_start()
- the connectionlines should be inside an include
- the following code can be optimized


$query = "SELECT * FROM user WHERE uname = '$username'";
$result = mysql_query($query, $db) or die(mysql_error());
$numRows = mysql_num_rows($result);
for ($count = 0; $count < $numRows; $count++) {
$resultArray = mysql_fetch_array($result);
}

$uname = $resultArray["uname"];
$pword = $resultArray["pword"];

if (($username == $uname) && ($password == $pword)) {

There is absolutely no point in select the complete usertable! --> use the username and pwd in a where clause. Look at the code below: only 1 variable-value pair is returned, and that gives you the same info, with far less trafic (imagen you have a usertable of a few 1000 records ...)
and you don't need that count and for-loop --> use a while loop to loop through recrdsets.
you should also check for sql-injection attacks, specially if you don't hash the passwords! --> if you only return the count, then an sql attack probably wount work unless they can slip in a LIMIT clasue, but that's unlikely. Still it's better to run an explicit check.

so your code could better look like


$query = ("SELECT Count(*) as numrec FROM user WHERE username='" . $username . "' AND password='" . $password . "'");
$result = mysql_query($query,$db) or die ('Queryproblem: ' . mysql_error());
if ($result){
$row=mysql_fetch_assoc($result);
mysql_free_result($result) // free resources from recordset --> not necessary here
if ($row['numrec'] != 1){
echo 'nope';
die() // stops scriptexecution
} else {
your code if login succeeds.
}
}


<edit>
Posts from sitami crossed mine typing in.

The last post about the selfreferencing form makes me believe that you have register_globals set to on (older version ?)
Then you certainly need to try to change the sessionvariables !
</edit>

sitami
01-25-2004, 12:58 AM
rafs explaination was better lol

its too early in the morning for me to think :S

raf
01-25-2004, 01:12 AM
Originally posted by sitami
rafs explaination was better lol

its too early in the morning for me to think :S
:D It's 2 o'clock for me

temper,

you better also not rely on shorttags (which aren't always enabled) so better use <?php ?> instead of <? ?>.
And while we're ripping the code appart (sorry, no bad intended), you might as well have some propper html-code and try to avoid slipping in and out php-mode.
So


if ((!$username) || (!$password)) {
?><center><form name=login method=post action="<? $php_self ?>">
<? echo ...

would be


if ((!$username) || (!$password)) {
echo ('<center><form id="login" name="login" method="post" action="' . $_SERVER['PHP_SELF'] . '">');
echo ...


(even if this all doesn't solve your problem, it would at least have become better buggy code :))

sitami
01-25-2004, 01:17 AM
2am lol .. im usually awake til 6am but its startin to affect me now lol
yeah i agree with raf .. embed the html into the php code liek raf suggested. makes your code look a lot neater + helps eradicate common mistakes .. thats what i found anyway :D

Temper
01-25-2004, 01:36 AM
Hey guys, thanks for the help. My code is more efficient now, but sadly I still don't stay logged in when I excecute the script. I'm using the code that raf posted, and I used some of the other suggestions given to me, but it wants to be stubborn. Could it not be keeping the session because I'm running the script in an included file?

the index.php file now looks like:


<?
session_start(); // I have to start the session here, or it won't work
include ("inc/htmlfns.php");
do_html_head();
include("inc/leftcon.php"); // I include the login script here.
do_html_middle();
?>

<!-- MAIN CONTENT HERE -->


Blah Blah Blah

<!-- END MAIN CONTENT -->
<? do_html_footer(); ?>



This is the leftcon.php file now:



<?

// I used to have a session_start() on this page, but it didn't make any difference.
$db = mysql_connect ("localhost", "*****", "*****") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("*****");

$username = $_POST['username'];
$password = $_POST['password'];

if ((!$username) || (!$password)) {
echo ('<center><form id="login" name="login" method="post" action="' . $_SERVER['PHP_SELF'] . '">');
echo '<center>You are not logged in</center>
Username: <input type=text name=username class="small" size="16">
Password: <input type=password name=password class="small" size="16">
<center><input type=submit value=Login></center>
<center>Click here to register</center>
</form></center>';
}
else {

$query = ("SELECT Count( * ) AS numrec FROM user WHERE uname = '" . $username . "' AND pword = '" . $password . "' ");
$result = mysql_query($query,$db) or die ('Error:' . mysql_error());
if ($result){
$row = mysql_fetch_assoc($result);
mysql_free_result($result);
if ($row['numrec'] != 1){
echo 'nope';
die(); // stops scriptexecution
} else {
$_SESSION['sesusername'] = $username;
$_SESSION['sespassword'] = $password;

}
}
}

if ($action == "logout") {
session_unregister("sesusername");
session_unregister("sespassword");
}
?>


Any ideas what I'm doing wrong? Is it not working perhaps because I declare the session_start in the index.php file, and the login script is included, thus for some reason not interacting with the index.php file?

Thanks in advance.

Temper
01-25-2004, 03:46 PM
I hate sounding rude, but can anyone help me?

raf
01-25-2004, 09:40 PM
Whether the code is inside an include or not makes no difference.

Lets try some clasic debugging and change


$query = ("SELECT Count( * ) AS numrec FROM user WHERE uname = '" . $username . "' AND pword = '" . $password . "' ");
$result = mysql_query($query,$db) or die ('Error:' . mysql_error());
if ($result){
$row = mysql_fetch_assoc($result);
mysql_free_result($result);
if ($row['numrec'] != 1){
echo 'nope';
die(); // stops scriptexecution
} else {
$_SESSION['sesusername'] = $username;
$_SESSION['sespassword'] = $password;

}
}

into


$query = ("SELECT Count( * ) AS numrec FROM user WHERE uname = '" . $username . "' AND pword = '" . $password . "' ");
echo ('Executed query = ' . $query ); // remove after debugging
$result = mysql_query($query,$db) or die ('Error:' . mysql_error());
if ($result){
$row = mysql_fetch_assoc($result);
echo ('<br />Number of matched rows = ' . $row['numrec'] ); // remove after debugging
mysql_free_result($result);
if ($row['numrec'] != 1){
echo 'nope';
die(); // stops scriptexecution
} else {
echo ('<br />Logged in now'); // remove after debugging
/* If you see the 'logged in now' on screen, then the session should be set. So were gonne print then*/
$_SESSION['sesusername'] = $username;
$_SESSION['sespassword'] = $password;
die ('<br />sesusername = ' . $_SESSION['sesusername']); // remove after debugging
/* The scriptexecution is stoppen after the sessionvar is printed.
If no value is printed for the sessionvar, then your PHP version is probably
lower the 4.0.6 and then you need to use
$HTTP_SESSION_VARS['sesusername'] = $username;


If a value is printed, then the problem must lie further down i the script
Then add
echo ('action=' . $action);
or else the problem is somewhere iside code tou didn't include */
}
}

which will tell you what i going on. Then check the comments above and add the extra code i suggest inthere.

It might also be intresting to include
phpinfo() ;
inside a page and then look if register_globvals in on and what php version your using.

Temper
01-25-2004, 11:38 PM
Thanks for the help, but for some reason I still have trouble. I checked my phpinfo(); and register_globals is turned on, and my server is running php 4.3.3.

I think to help you understand I'll give you a link to the site.
See what if you can see what's going on when you log in @http://www.pwcs.ca/index.php

The code for the index.php file is the same, and the leftcontent now looks like this: (note, I removed all the "die" commands since the layout is before and after the login script, and I want the page to load).


<? session_start(); ?>
<a href="http://www.pwcs.ca/index.php">Test Session 1</a><br>
<a href="http://www.pwcs.ca/index2.php">Test Session 2</a><br>
<br><br><br>

<?

$db = mysql_connect ("localhost", "****", "****") or die ('I cannot connect to the database because: ' . mysql_error());
mysql_select_db ("pwcs36_db");


$username = $_POST['username'];
$password = $_POST['password'];

if ((!$username) || (!$password)) {
echo ('<center><form id="login" name="login" method="post" action="' . $_SERVER['PHP_SELF'] . '">');
echo '<center>You are not logged in</center>
Username: <input type=text name=username class="small" size="16">
Password: <input type=password name=password class="small" size="16">
<center><input type=submit value=Login></center>
<center>Click here to register</center>
</form></center>';
}
else {

$query = ("SELECT Count( * ) AS numrec FROM user WHERE uname = '" . $username . "' AND pword = '" . $password . "' ");
echo ('Executed query = ' . $query ); // remove after debugging
$result = mysql_query($query,$db) or die ('Error:' . mysql_error());
if ($result){
$row = mysql_fetch_assoc($result);
echo ('<br />Number of matched rows = ' . $row['numrec'] ); // remove after debugging
mysql_free_result($result);
if ($row['numrec'] != 1){
echo 'nope';
} else {
echo ('<br />Logged in now'); // remove after debugging
/* If you see the 'logged in now' on screen, then the session should be set. So were gonne print then*/
$_SESSION['sesusername'] = $username;
$_SESSION['sespassword'] = $password;
echo ('<br />sesusername = ' . $_SESSION['sesusername']); // remove after debugging
/* The scriptexecution is stoppen after the sessionvar is printed.
If no value is printed for the sessionvar, then your PHP version is probably
lower the 4.0.6 and then you need to use
$HTTP_SESSION_VARS['sesusername'] = $username;


If a value is printed, then the problem must lie further down i the script
Then add
echo ('action=' . $action);
or else the problem is somewhere iside code tou didn't include */
}
}

}
if ($action == "logout") {
session_unregister("username");
session_unregister("password");
}
?>


Thank you for taking the time to help me out so much so far. :)

Temper
01-27-2004, 05:10 PM
I'm only going to bump it this last time, so I won't annoy you guys too much. I just don't know what to do. :(

raf
01-27-2004, 08:02 PM
OK. So everything for the login is fine and you are logged in and the sessions or set.

So read the comment and use the

echo ('action=' . $action);

to see what value it has. If it is (logout', then that is the problem. If its not, then your problem is inside other code that is executed later on in some code you don't show here.

Temper
01-27-2004, 09:48 PM
I've read up on sessions some more and I've made some changes to the script, and I stay logged in now (the sessions work), and I'm wondering if the way I have it done is good.

instead of



$username = $_POST['username'];
$password = $_POST['password'];

if ((!$username) || (!$password)) {
echo ('<center><form id="login" name="login" method="post" action="' . $_SERVER['PHP_SELF'] . '">');
echo '<center>You are not logged in</center>

...........................


I've changed it to



if((!$username) || (!$password)){
$_SESSION['username'] = $_POST['username'];
$_SESSION['password'] = $_POST['password'];
$username = $_SESSION['username'];
$password = $_SESSION['password'];
}



Is this a good way to code it?

raf
01-27-2004, 10:27 PM
Euh ... no.

First of all. Inside your other code, you have

$_SESSION['sesusername'] = $username;
$_SESSION['sespassword'] = $password;
...
if ($action == "logout") {
session_unregister("username");
session_unregister("password");
}

==> you need to rename these sessionvariables.


But more in general: why do you want to store the username and pwd inside the sessionvariables? Normally, you would just set a flag, like
$_SESSION['loginprofile'] = 1
and check against that sessionvariable. This way you can also choose a unique variablename to avoid problems with your globals + you can store a profile inthere to determine if that user can see a certain page.
For instance, by giving the admin a $_SESSION['loginprofile'] = 10
and the regular loged in user a $_SESSION['loginprofile'] = 2 and then specify on top of each page which minimal value you need to have inside the $_SESSION['loginprofile'] to access the page.

Temper
01-27-2004, 10:41 PM
The reason I do that is because I'm just learning about sessions and really have no clue (as you've probably seen by now). Could you give me an example of I could log people in using flags instead of what I'm doing now?

raf
01-27-2004, 11:16 PM
OK. When you process the login, you do something like


$query = ("SELECT userprofile FROM user WHERE uname = '" . $username . "' AND pword = '" . $password . "' ");
$result = mysql_query($query,$db) or die ('Error:' . mysql_error());
if (($result) and (mysql_num_rows($result) == 1)){
$row = mysql_fetch_assoc($result);
mysql_free_result($result);
$_SESSION['loginprofile'] = $row['userprofile'];
} else {
echo ('Sorry. You can not log in. Try again.)
}


So you need to add a column inside your user - table with the profile-value for each user.

Then on top of each page, you can have


$pagesecprof = 2 ; // --> a vairable with the minimum required securityprofile
include ('includes/securitycheck.php'); // an include that checks if the user has sufficient permission. Cna be placed anywhere

Nothing special there. On top of each page you set the minimum required userprofile and include the include() statement. An admin-module like usermanagement will probably have $pagesecprof = 10,but a less sensitive page could be alreay available for people with a profile of 2

Inside securitycheck.php you then have something like


if (!isset($_SESSION['loginprofile'])){
header('Location: login.php'); // specify the loginpage inthere.
die();
} elseif ($_SESSION['loginprofile'] < $pagesecprof){
echo ('You do not have sufficient permissions to request this page.');
die ();
} else {
/*do something here like setting the pageadress in a session-variabele
or if you want to keep track of the user or whatever*/
}


You see? It hardly 10 lines of code to implement a securitysystem which even allows you to ue permissionprofiles

Temper
01-28-2004, 01:26 AM
Ah, I must say thank you so much, you've helped me out a lot and I'm really grateful. I've got this up and running and a major part of that is because of you. :D

I only have one last question before I leave this thread alone:
What's the difference between
$_SESSION['username']
and
$_SESSION['sesusername'] ?

does the "ses" do anything aside from let you know that it's part of a session?
Thanks
-Mike

raf
01-28-2004, 07:25 AM
You're welcome.

About the sessionvariablename
It doesn't do anything. It's just the variablename, but if you have register_globals=on, then i would make sure you always have unique variablenames, even across collections. So having $username and also $_POST['username'] and also $_SESSION['username'] isn't realy the best way to go then.

But it's also kind of a codingconvention to have meaningfull variablenames that indicate the 'origin' or the datatype (like $strtitle, $datestartpoint, $intage etc
or if you include the collection:
$formintage etc



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum