/    Sign up×
Community /Pin to ProfileBookmark

Problem with php login page

I found a tutorial on how to create simple login functionality with php and mysql but I can’t get it to work as I want. I would really appreciate if someone could take a look at the code and let me know what’s wrong. What I don’t get is why it’s not redirecting to the “area.php” page even if I enter a valid user/password combination. Even if I enter a wrong user/password combo it doesn’t trigger the “invalid username/password combination” on line 52 in the code below.

THE login.php FILE

[code=php]<?php
//Connect to database
mysql_connect(“localhost”, “root”, “my_password”);
mysql_select_db(my_database);

if($_POST[username] != “” || $_POST[password] != “”){
$login_status = login($_POST[username], $_POST[password]);
}
elseif($_GET[logout]){
logout();
}
$userid = status();

function status(){
$sessionid = $_COOKIE[test_account];
$oldtime = time() – 3600;
$query = mysql_query(“SELECT * FROM user_sessions WHERE
sessionid = ‘$sessionid’ AND timestamp > ‘$oldtime'”);
if(mysql_num_rows($query) == 1){
$info = mysql_fetch_array($query);
return $info;
}
else {
return 0;
}
}

function login($username, $password){
$username = addslashes($username);
$password = md5($password);
$query = mysql_query(“SELECT * FROM user_accounts WHERE username = ‘$username’ AND password = ‘$password'”);
if (mysql_num_rows($query) == 1){
$info = mysql_fetch_array($query);
$userid = $info[userid];
$sessionid = md5($userid . time());
$time = time();
@setcookie(‘test_account’, $sessionid, $time + 3600, ‘/’, ”);
mysql_query(“DELETE FROM user_sessions WHERE userid = ‘$userid'”);
mysql_query(“INSERT INTO user_sessions (sessionid, userid, timestamp) VALUES(‘$sessionid’,’$userid’,’$time’)”);
return $userid;
}
else{
return 0;
}
}

if($userid > 0){
header(“Location: area.php”);
}
else{
if($login_status != ” && $login_status == 0){
echo “invalid username/password combination<br>”;
}
?>
<h1>Login</h1>
<form action=”login.php” method=”POST”>
Username <input type=”text” name=”username” />
Password <input type=”password” name=”password” />
<input type=”submit” value=”Log In” />
</form>
No account? <a href=”register.php”>Register</a>
<?php } ?>[/code]

THE area.php file

[code=php]
<?php
function status(){
$sessionid = $_COOKIE[test_account];
$oldtime = time() – 3600;
$query = mysql_query(“SELECT * FROM user_sessions WHERE
sessionid = ‘$sessionid’ AND timestamp > ‘$oldtime'”);
if(mysql_num_rows($query) == 1){
$info = mysql_fetch_array($query);

return $info;
}
else {
return 0;
}
}

$userid = status();
?>

<?php
if ($userid > 0) {
echo “welcome to user area”;
}
?>

<?php
function logout() {
$sessionid = $_COOKIE[test_account];
@setcookie(“test_account”, time() – 9999, ‘/’, ”);
mysql_query(“DELETE FROM user_sessions WHERE sessionid = ‘$sessionid'”);
}
?>[/code]

THE register.php FILE

[code=php]<?php
mysql_connect(“localhost”, “root”, “my_password”);
mysql_select_db(my_database);

if($_POST[username] != “” || $_POST[password] != “”){
$login_status = register($_POST[username], $_POST[password]);
}
else {
printTable();
}

function register($username, $password){
$username = addslashes($username);
$password = md5($password);
$query = mysql_query(“SELECT * FROM user_accounts WHERE username = ‘$username'”);
if (mysql_num_rows($query) == 1){
echo “username already exists<br>”;
printTable();
}
else{
mysql_query(“INSERT INTO user_accounts (username, password) VALUES (‘$username’, ‘$password’)”)or die(mysql_error());
echo “You successfully registred.”;
}
}

function printTable() {
?>
<h1>Register</h1>
<form action=”register.php” method=”POST”>
Username <input type=”text” name=”username” />
Password <input type=”password” name=”password” />
<input type=”submit” value=”Log In” />
</form>
<?php } ?>[/code]

Thanks for any help!

to post a comment
PHP

12 Comments(s)

Copy linkTweet thisAlerts:
@PierceMooreJun 12.2009 — Hey there, again.

I am looking through some of your code, and though it may just be me, I think you may have issues in your SQL queries...

[code=php]$query = mysql_query("SELECT * FROM user_accounts WHERE username = '$username' AND password = '$password'");[/code]

I have always wrapped variables in SQL Queries in {} brackets. That would make your code:

[code=php]$query = mysql_query("SELECT * FROM user_accounts WHERE username = '{$username}' AND password = '{$password}'");[/code]

Just a thought, I will let you know if I see something else that pops out :-)
Copy linkTweet thisAlerts:
@xkrjaauthorJun 12.2009 — And thanks, again.

I added brackets but it didn't make any difference. Worth to mention is that the register.php seems to work as supposed. Users are added in the database.
Copy linkTweet thisAlerts:
@PierceMooreJun 12.2009 — Ah, cool, maybe I am doing it wrong :-)

I am digging here, and as kind of a rookie I haven't seen anything that has jumped out yet, but I did see this:

[code=php]if($_POST[username] != "" || $_POST[password] != ""){
$login_status = login($_POST[username], $_POST[password]);
} [/code]


You are giving the user the option to leave at least one of the fields empty. While that will not affect the outcome of the query, it seems like it would save time and a few database queries if you did something like this:

[code=php]if((strcmp($_POST[username],'') != 0) && (strcmp($_POST[password],'') != 0)){
$login_status = login($_POST[username], $_POST[password]);
} [/code]


Additionally, I would recommend changing the way you are checking to see if a username is already registered. Your code:

[code=php]$query = mysql_query("SELECT * FROM user_accounts WHERE username = '$username'");
if (mysql_num_rows($query) == 1){
echo "username already exists<br>";
printTable();
} [/code]


If, for some crazy reason, MySQL returned a result that was, say, 2 (or something besides 1), your query would insert the username again, and cause more confusion down the road. Perhaps try this:

[code=php]$query = mysql_query("SELECT COUNT(*) FROM user_accounts WHERE username = '$username'");
if (mysql_result($query,0) > 0){
echo "username already exists<br>";
printTable();
} [/code]


Just a thought. I promise I am just a little bored and not trying to nitpick your code in any way. This is a learning experience for me, as well. :-)

Pierce
Copy linkTweet thisAlerts:
@xkrjaauthorJun 12.2009 — Thanks Pierce,

Both are good suggestions. I'll change this. I tried to be critical when I wrote down the code from the tutorial but som things slipped through.

Regarding the {}-brackets: I'm pretty sure I've seen both solutions :-)

Do you have a working debugger? I'm waiting for some forum help with an issue I have with the Komodo-Editor so I don't have a debugger just yet.
Copy linkTweet thisAlerts:
@PierceMooreJun 12.2009 — Excellent! I promise I am not trying to be naggy :-)

Personally, I use and love PHPDesigner (found here). Definitely try the trial, as it comes with a powerful debugger, as well as the best dynamic syntax highlighting ever seen by man.

The software itself is a bit expensive, and does not yet support SFTP (HUGE bummer), but its debugger is quite powerful.

Definitely something to check out ?

And the reason that I suggested the change for the way you checked to see if the fields were empty is this: (as a rookie myself, I never did this until I got smacked around by a PHP Genius for not doing it :-P )

Saying if($str1 != '') will compare the two based on the first character only, as I understand. While this will work for an empty quote-set (''), it will not work for, say:

$str1 = 'A';

$str2 = 'ABCASKFNOPAISNFOPLIAJSLFA)IK_)R_IU$K_)I%RQASF_)I%';

if($str1 == $str2) {

// code

}

as the first characters are the same. The strcmp() function (string compare) analyzes all characters of the strings to ensure that they are identical for all characters.

This is really just a best-practices thing that will come to good use in the future. ?
Copy linkTweet thisAlerts:
@xkrjaauthorJun 12.2009 — Aha, good explanation :-)

First I just saw the &&-characters and thought it was a good idea to change to that but then I noticed the strcmp() you've added. Certainly a better approach.

Ok, but no idea why the login script doesn't behave the way I want it? The two database tables I use for this are the following:

Table name: user_accounts

Field 1: userid, int(10), primary key, auto_increment

Field 2: username, varchar(10)

Field 3: password, varchar(32)

Table name: user_sessions

Field 1: sessionid, varchar(32), primary key

Field 2: userid, int(10)

Field 3: timestamp, int(12)

(To give the guy who created the tutorial a little credit it's located here)

I'll give Komodo a chance before I switch to something commercial. If I get it up and running that is :-)
Copy linkTweet thisAlerts:
@PierceMooreJun 12.2009 — Thank you ?

For the record, I just checked this code (all sections) in PHPDesigner, and all the PHP is valid. This is odd and confusing to me, as that generally means (with PHP at least) that this should be a working system.

Perhaps your cookies are not setting right? Have you tried running print_r($_POST) yet after submitting the username and password form instead of allowing the script to work with the database yet?

Incrementally stopping the broken script in its angry tracks is often the way I find errors in my scripts :-)

Moral of this story: print_r($_POST) as often as possible in between steps to ensure that all necessary data is being posted at the correct times.

Please do let me know how it goes :-)

Pierce
Copy linkTweet thisAlerts:
@PierceMooreJun 12.2009 — And, unless I am mistaken, Komodo IDE is about as commercial as it gets...

PHP Designer is muuuuuuuuuuuuch cheaper than that...
Copy linkTweet thisAlerts:
@xkrjaauthorJun 12.2009 — My brain is overheated...

I've been working on this for hours now but haven't solved it yet. I think I'm close though but right now I would really appreciate if someone could take a look at the code below.

What I've found out is that there is a "lag" between the setcookie $sessionid and the $_COOKIE $sessionid. I mean that if I first type in a username and password and then submit the page there is no $_COOKIE $sessionid found in the status()-function but if I type in a username and password again it suddenly matches the $sessionid that was set by the setcookie-function earlier!?

Does anyone understand this?

Pierce, I'm using the Komodo-Edit. It's an open-source version of the Komodo-IDE, and free :-)

[code=php]<?php
//Connect to database
mysql_connect("localhost", "root", "my_password");
mysql_select_db(my_database);

function login($username, $password){
$username = addslashes($username);
$password = md5($password);
$query = mysql_query("SELECT * FROM user_accounts WHERE username='$username' AND password='$password'");
if(mysql_num_rows($query) == 1) {
$info = mysql_fetch_array($query);
$userid = $info['userid'];
//echo "userid = " . $userid . "<br>";
$sessionid = md5($userid . time());
echo "sessionid fr&#229;n login: " . $sessionid . "<br/>";
//echo "sessionid = " . $sessionid;
$time = time();
@setcookie('test_account', $sessionid, $time + 3600, '/', '');
mysql_query("DELETE FROM user_sessions WHERE userid = '$userid'");
mysql_query("INSERT INTO user_sessions (sessionid, userid, timestamp) VALUES('$sessionid','$userid','$time')");
return $userid;
}
else{
return 0;
}
}

function status() {
$sessionid = $_COOKIE['test_account'];
echo "sessionid fr&#229;n cookie: " . $sessionid . "<br/>";
$oldtime = time() - 3600;
echo "oldtime: " . $oldtime . "<br/>";
$query = mysql_query("SELECT * FROM user_sessions WHERE sessionid='$sessionid' AND timestamp>'$oldtime'");
echo "match: " . mysql_num_rows($query) . "<br/>";

if(mysql_num_rows($query) == 1) {
$info = mysql_fetch_array($query);
echo " info = " . $info . "<br/>";
return $info['userid'];
}
else {
return 0;
}
}

if((strcmp($_POST[username],"") != 0) && (strcmp($_POST[password],"") != 0)){
$login_status = login($_POST[username], $_POST[password]);
}
elseif($_GET[logout]){
logout();
}

$userid = status();

if($userid > 0){
//header("Location: area.php");
echo "login correct <br/>";
}
else{
if($login_status != '' && $login_status == 0){
echo "invalid username/password combination<br>";
}
?>
<h1>Login</h1>
<form action="login.php" method="POST">
Username <input type="text" name="username" />
Password <input type="password" name="password" />
<input type="submit" value="Log In" />
</form>
No account? <a href="register.php">Register</a>
<?php } ?>[/code]


Thanks for help!
Copy linkTweet thisAlerts:
@PierceMooreJun 12.2009 — Ah, I see. I will look into Komodo-edit personally ?

And I looked at your code, and you definitely have all the information displaying. Is it all correct? You said that there seems to be a lag in the time that the script first runs and the time that the cookie/sessionid actually displays correctly. This is surely mind-boggling.

Database-driven session handling is always a little tricky, especially when you are not well versed in cookies (myself, for example). It is for this reason that I generally stick to $_SESSION[''] based handling of user's login status. It may require them to log back in every time, but the $_SESSION[''] var has a timeout that you can control, much like a cookie. Additionally, it is much more flexible with regard to code, as you need only call session_start() at the beginning of your code.

One more thing, though, while I am thinking about it.

Have you considered creating a "config.php" file, and just using a PHP include with it in all your pages? This way, you need only modify it once to update all pages. For example:

[code=php]
<?php

require_once('config.php');

?>
[/code]


And the example config.php file:

[code=php]
<?php
session_start();

// Establish DB connectivity information
$databasehost = 'localhost';
$databaseuser = 'dbusername';
$databasepass = 'dbpassword';
$databasename = 'dbname';
$databasetype = 'mysqli';

mysql_connect($databasehost,$databaseuser,$databasepass);

//echo 'Connected to Localhost<br>';

mysql_select_db($databasename) or die ( "Whoops! Unable to Establish a Connection with Database!" );

include('functions.class.php');

?>

[/code]


This is just a thought. :-)

Dreaming.. perhaps a database variable is not entered correctly in one of the pages?
Copy linkTweet thisAlerts:
@xkrjaauthorJun 13.2009 — Pierce,

Once again. Thanks for the help. I finally understood what the problem was and I rewrote the script and now it works! The problem was that a cookie was created and in the same postback the cookie was read and that is not possible since the cookie will then contain the previous set cookie value. Now I create a session with session_start() and if the login is successful I set a $_SESSION variable to true AND I also create a cookie. Then the user is directed to the members area and the script in the members area checks if the user has a valid session or a valid cookie.

I will certainly check out the 'include' closer now when I can relax a bit :-)

See you around!
Copy linkTweet thisAlerts:
@PierceMooreJun 14.2009 — Excellent! Not a problem! I am sincerely happy to help!

I promise you that $_SESSION is definitely flexible and amazing. Way easier to manage and handle.

I use the php include() function as an integral part of any web presence that I have ever designed, as it allows you to modify one individual file to update all pages that require that file. Just a thought :-)


Definitely see you around here :-)

Pierce
×

Success!

Help @xkrja spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.16,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...