How to recognize ADMINISTRATOR at login

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
User avatar
diseman
Forum Contributor
Posts: 174
Joined: Mon Jul 26, 2010 1:30 pm
Location: Florida

How to recognize ADMINISTRATOR at login

Post by diseman »

Hello Experts,

My Level = Beginner

Working on a fictitious site to learn PHP.

I have some code I found that allows me to check a mySQL table for Username & Password and if found let's me in. Perfect. But now, I entered an ADMIN userid & password in the table and assigned its USERTYPE '5' where as the other account level I make '0.'

I was messing around with it for a while, but then realized my login script is checking the values I enter on the form against the values in the database and I don't know how to also make it check the USERTYPE for 5, so I can be directed to a different page than the person who has a USERTYPE of 0.

So, here's what I have. Can someone tell me if this is where I need to put something to check USERTYPE? Examples are greatly appreciated, but I don't mind a mystery if you can point me in the right direction. I'm good at Google'ing. Here it is:

Code: Select all

<?php session_start();

include ("../_config/_config.php");

// Connect to server and select databse.

mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

// username and password sent from form

$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

// To protect MySQL injection (more detail about MySQL injection)

$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";

$result=mysql_query($sql);

// Mysql_num_row is counting table row

$count=mysql_num_rows($result);
// If result matched $myusername and $mypassword, table row must be 1 row

if($count==1){

// Register $myusername, $mypassword and redirect to file "login_success.php"

if (empty($_SESSION['myusername']))
session_register('myusername');
$_SESSION['myusername'] = $myusername ;

if (empty($_SESSION['mypassword']))
session_register('mypassword');
$_SESSION['mypassword'] = $mypassword ;

header("location:../templates/contact.php");
}
else {
echo "Wrong Username or Password";
}
?>
Hope my request for help makes sense...

Any help with the logic of this thing would be great.

Thank you...
cpetercarter
Forum Contributor
Posts: 474
Joined: Sat Jul 25, 2009 2:00 am

Re: How to recognize ADMINISTRATOR at login

Post by cpetercarter »

Where is 'usertype' stored? Is it one of the columns in the table which stores usernames and passwords? That would be the logical place to put it. If so, you can read it from the result of your database query, and cause different things to happen by using a simple 'if' statement.

I know that you are only constructing a fictitious site for learning purposes, but it is a really bad idea, from a security point of view, to put usernames and passwords into the sesssion variables. Passwords should never leave the database. And you really have no need to do this. Just have a session variable called eg 'status' - set it to 'logged in' for a user who is logged in, or to 'logged in admin' for an admin user who is logged in etc. I think you get the idea.

Also, you do not need to use 'session_register()' - indeed you ought not to do so, as the function is deprecated in the latest versions of php. The accepted way of writing to session variables is to start/resume a session with 'session_start()' and then use statements like $_SESSION['status'] = 'logged in';

Finally - and at some danger of making you totally fed up with me - see if you can structure your site so that you can send the user to a new page without using 'header (location...' . It is very inefficient. A better approach is to structure things so that you 'require()' the code for different web pages at the appropriate points in your script.
User avatar
diseman
Forum Contributor
Posts: 174
Joined: Mon Jul 26, 2010 1:30 pm
Location: Florida

Re: How to recognize ADMINISTRATOR at login

Post by diseman »

Hi cpetercarter,

Glad to see your name again - although I think you were confused about who you were talking to when you wrote your reply! LOL Remember, I'm a beginner with maybe two weeks under my belt and self-taught through trial & error and with the help of people like yourself. I completely understand what you're saying, but I don't have a lot to go on. Even Google'ing is no good, because I don't know the terminology to search -> because I don't know how to do it. :) So, let me reply back with my thoughts...

1. Yes, 'usertype' is a column in the 'users' table.

2. My first instinct was to update/change the login code to check 'username' & 'password' & 'usertype' and to update the IF portion of the code. I thought I was onto something, but then failed. I changed it to something like this:

Code: Select all

$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword' and usertype='$usertype' ";
Then, in the IF statement area, I added '&&' and put something in about $usertyp=5'.... That's when it occurred to me. I think the way I did it is wrong because it would require me to have had a menu list in my login form where I would have had to choose a usertype I was because the code above would have been looking for such a _POST. That's when I realized, I don't know how to search a table based on 'username' & 'password' , but also another field in the db that isn't passed along in the form from the start. I even hacked around with <input type="hidden".... but then again the value="" would have had to have something in there. So, you get the point. I was spinning my wheels and getting nowhere.

So, can you show me how to search 'username' and 'password' and then look for a value in another column that wasn't included in my form .. OR .. give me some keywords I can use to Google because when you don't know the PHP function that would apply here, it's hard to Google an answer.

3. You know, the first time I read your comment about passing passwords around in a session, I only got 1/2 of your meaning I think. Then it occurred to me while looking at the code more that I'm passing the username and password back & forth every time I go to another page in my site and throughout the entire visit. If that's the case, that doesn't sound good; even to a beginner.

I found that login code somewhere on the Internet. It was my first experience with $_SESSION. I was impressed that I actually coded a site with PHP and a credential system. :) OK, I'll keep that in mind. I'll try and find some code somewhere that does it this way, but I'm not having much luck finding a good login script that doesn't cost $150.

4. Not even close to getting fed up. That's the nice thing about having a fictitious site. I don't have a suspense date and no one's waiting for it. I do want to keep moving forward if/when possible, but I'll go back and fix it if it's blatantly wrong. I think I understand what you're saying about HEADER vs REQUIRE(), but not sure how that would be accomplished from a login page where the user has to be taken somewhere - automatically - upon entering proper credentials. I'll search this some more as well and see what I learn...

I could really use some help with #2 above if you have time. Seems that will be a good thing to know in the future..

Thank you...
User avatar
PHPHorizons
Forum Contributor
Posts: 175
Joined: Mon Sep 14, 2009 11:38 pm

Re: How to recognize ADMINISTRATOR at login

Post by PHPHorizons »

Hello diseman,

#2 The first thing to do is drop that usertype portion of that query. Your main goal is to get the user's data from the database. You only need a username and password for that. Once you have the user's data, then you can begin to check usertype and take appropriate action.

Code: Select all

$sql="SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword'";
$result = mysql_query($sql);

if ($result and mysql_num_rows($result) > 0) {
    $user_data = mysql_fetch_array($result);
    if ($user_data['usertype'] == 0) {
        
    } else if ($user_data['usertype'] == 1) {
        
    } else if ($user_data['usertype'] == 2) {
        
    } else if ... { ... }
}
#4 Using a header redirect upon successfully logging in is fine to do. I use that method, and so do many sites. I think a meta refresh is a good way to go because it has a delay of xxx seconds and the user can be thanked for logging in, notified that they are being redirected to the website, and given a link to go there immediately (the same thing that happens after posting in a forum, right).

Cheers

Edit:
Changed

Code: Select all

if ($result and mysql_num_rows($sql) > 0) {
to

Code: Select all

if ($result and mysql_num_rows($result) > 0) {
Last edited by PHPHorizons on Sun Aug 15, 2010 12:11 pm, edited 1 time in total.
User avatar
diseman
Forum Contributor
Posts: 174
Joined: Mon Jul 26, 2010 1:30 pm
Location: Florida

Re: How to recognize ADMINISTRATOR at login

Post by diseman »

Thank you PHPHorizons for that wonderful example; +5 for you. I've been working on it since you posted it and just finished getting it to work. For some reason, the

Code: Select all

if ($result and mysql_num_rows($sql) > 0) {
was giving me an error. After hacking at it for a while, Google'ing, and using pieces from here and there, I was able to get this to work

Code: Select all

if ($result && $count == 1) {
.

Again, thank you for your example. Seeing it makes perfect sense now. Hopefully, I should be able to use this whenever something like this comes up again.

Also, looking at the $_SESSION stuff a little more closely, it appeared to me that it would still all work if I took out the part about password. I took that out and it's still good. I know it's not the fix cpetercarter was talking about, but I still have to look that up and see what I find and how to do it. I actually stumbled on a posting where they guy has it just like it's been suggested with the 'logged_in.'

So, I'm going to see what I can find on that now and I'm going to post the working code in case anyone else learning PHP is stuck on the same thing:

Code: Select all

<?php session_start();

require ("../_config/_config.php");

mysql_connect("$host", "$username", "$password")or die("cannot connect");
mysql_select_db("$db_name")or die("cannot select DB");

$errormsg = "" ;

// username and password sent from form

$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

// To protect MySQL injection (more detail about MySQL injection)

$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$myusername = mysql_real_escape_string($myusername);
$mypassword = mysql_real_escape_string($mypassword);

$sql = "SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword' ";

$result = mysql_query($sql);

$count=mysql_num_rows($result);

if ($result && $count == 1) {
	
    $user_data = mysql_fetch_array($result);
   
		if 		($user_data['usertype'] == 0) {
	
					require ("../_includes/session_login.php");
	
					header("location:../templates/contact.php");
				
		} else if ($user_data['usertype'] == 1) {

		     		require ("../_includes/session_login.php");
	
					header("location:../templates/admin_main.php");
				
				
		} else if ($user_data['usertype'] == 2) {

		     		require ("../_includes/session_login.php");
	
					header("location:../templates/admin_main.php");
	    
	    
    		} else if ($user_data['usertype'] == 5) {

		     		require ("../_includes/session_login.php");
	
					header("location:../templates/admin_main.php");
		}

}

else {
	$errormsg = "Wrong Username or Password";
     }

?>
Some of the $_SESSION info is now being called into play by 'require,' so if you need it, look at my first posting before I did it this way and you can grab it there.
User avatar
PHPHorizons
Forum Contributor
Posts: 175
Joined: Mon Sep 14, 2009 11:38 pm

Re: How to recognize ADMINISTRATOR at login

Post by PHPHorizons »

You're welcome ;)

The code is looking pretty good. I do have some observations that might interest you, but first, I have to correct the code I posted for you. It was my error that caused the problem for you. You did find the right way to fix it.

Assuming the count of the rows in that result set doesn't need to be used more than once, the num rows call can go in the if block. I had the wrong variable passed into the function though. I used $sql, instead of $result. I have corrected my earlier post:

Code: Select all

if ($result and mysql_num_rows($result) > 0) {
Your code is fine though, and doesn't need to be changed.

Now for my observations: I noticed that you are storing passwords without hashing them. That is incorrect. When a user registers for the site, you need to put that password into the hash() function. I personally use $hashed_pass = hash('sha256', $password);
You will not need to use mysql_real_escape_string on the password once it is hashed. The sha256 password is (I think) 64 chars long.

When a user logs into your site, you would take the password and run it through that hash function again, and then use that hash in the query:

Code: Select all

$mypassword = hash('sha256', $mypassword);
...
$sql = "SELECT * FROM $tbl_name WHERE username='$myusername' and password='$mypassword' ";
There is no chance of mysql injection with this method. And if your db is ever compromised, the hacker will not have the plain text passwords of your users.

The second observation is that when you access the POST array, you need to check if the key you're using exists first. Otherwise, you can get an Undefined index error (depending on the error reporting level).

This code should be replaced with the next block of code:

Code: Select all

$myusername=$_POST['myusername'];
$mypassword=$_POST['mypassword'];

Code: Select all

$myusername= isset($_POST['myusername']) ? $_POST['myusername'] : null;
$mypassword= isset($_POST['mypassword']) ? $_POST['mypassword'] : null;
Cheers
User avatar
diseman
Forum Contributor
Posts: 174
Joined: Mon Jul 26, 2010 1:30 pm
Location: Florida

Re: How to recognize ADMINISTRATOR at login

Post by diseman »

Thanks again PHPHorizons.

Yes, I plan to use encryption for passwords. While learning, I wanted to see the passwords when I look at the database. However, you brought up a whole new set of problems with that comment. LOL Actually, when you posted the comment, I stopped what I was doing and went to do that just for the heck of it. Then I ran into some problems because of the way my site is designed to work. Instead of me registering myself to the website and selecting a password that I could easily encrypt, I create a user account with contact information and the password is automatically created based on the lastname where I add 123 to the end. The problem was that I then put the password.123 into the users table and then copy the lastname without 123 to the contact_info table at the same time. Well that wasn't so easy to figure out, so I went back to what I was doing and had a pretty good learning day today.

I will get to the password though pretty soon and when I do, I'll invite you to comment on the problem that stumped me. : )

Thank you again for some great tips..
User avatar
PHPHorizons
Forum Contributor
Posts: 175
Joined: Mon Sep 14, 2009 11:38 pm

Re: How to recognize ADMINISTRATOR at login

Post by PHPHorizons »

While learning, I wanted to see the passwords when I look at the database.
Completely understandable.
Thank you again for some great tips..
Absolutely, any time ;) Cheers
Post Reply