php login script and user management

Hi all,

I am pretty new to php and I am trying to write a login script that will authenticate users and also forward them to a particular page based on the type of user.

I have a user table

userid
username
password
lname
firstname
typeid (referenced from a table type which has 'user', 'admin', and 'manager' )


So what I want to do is once the user has been authenticated, we will look at the type of user and based on that they will be forwarded to the appropriate page(eg. userpage.php or adminpage.php etc) and display to the user what they are logged in as.  Thanks

ps. I am starting to write this application, so i will have more questions later..more points if you will be able to help me with this :)

aannanAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

gamebitsCommented:
<?

if($typeid == 'user'){ header("Location: http://www.yourdomain.com/user.php"); }

elseif($typeid == 'admin'){ header("Location: http://www.yourdomain.com/admin.php"); }

elsif($typeid == 'manager')header("Location: http://www.yourdomain.com/manager.php"); }

?>
       
0
aannanAuthor Commented:
how do the users get authenticated? and how do i prevent users from just bypassing authentication by just typing in the url if they know it?
0
rdivilbissCommented:
To get them authenticated you need a web form where they can enter their userid and password, then you post those values to a form handler page on which you do a lookup to validate the userid and password combination.

If they authenticate, look up their user level in the database and assigne that to their session. e.g. $_SESSION["userlevel"]="admin".

At the top of every protected page you check the session variable and if they do not have the required level you send them to an access violation page.

This is a large issue, not one simple question.  For a very good idea of all the decisions and variables you need to consider start here.

http://www.rodsdot.com/development/Authentication/default.asp

ASP not PHP, but the point is all the security considerations and the ways to handle them.

Once you have decided on your specific requirements we can write code to perform the necessary functions.  
0
Cloud Class® Course: Amazon Web Services - Basic

Are you thinking about creating an Amazon Web Services account for your business? Not sure where to start? In this course you’ll get an overview of the history of AWS and take a tour of their user interface.

BrianGEFF719Commented:
HEre is an example of how to perform authentication using mySql:

http://www.tutorialized.com/tutorial/Simple-reusable-PHP-MySQL-authentication-script/23914
0
mukhtar2tCommented:
You must use session variable to save user authentication
your login script would be like this:
<?php
session_start();
if(!($conn = mysql_connect($db_server,$db_user,$db_pass)))
exit('Cannot connect to db.');
if(!mysql_select_db($db_name))
exit('Cannot select a db.');

if(!($sql = mysql_query("select userid,username,typeid from user where username = $user_name and password = $password",$conn)))
exit('Query failed');

/* I preferred using mysql_real_escape_string function instead of passing the user and pass direct to the sql string*/

$user_row = mysql_fetch_assoc($sql);
switch($user_row['typeid'])
{
1: // user or you can use typename instead of typeid
$_SESSION['user_type'] = 'user';
$_SESSION['userid'] = $user_row['userid'];
$_SESSION['username'] = $user_row['username'];
// you can add any session variable as you like.
header('location: control.php'); // or any other page
break;
2: // admin or you can use typename instead of typeid
$_SESSION['user_type'] = 'admin';
$_SESSION['userid'] = $user_row['userid'];
$_SESSION['username'] = $user_row['username'];
// you can add any session variable as you like.
header('location: control.php'); // or any other page
break;
3: // manager or you can use typename instead of typeid
$_SESSION['user_type'] = 'manager';
$_SESSION['userid'] = $user_row['userid'];
$_SESSION['username'] = $user_row['username'];
// you can add any session variable as you like.
header('location: control.php'); // or any other page
break;
default:
exit('You are not authorized to view this page');
break;
}
?>
and on your control file you can write
<?php
session_start();
switch($_SESSION['user_type'])
{
'user':
echo "Hello User:$_SESSION[username]";
// do as you like for this user type
break;
'admin':
echo "Hello User:$_SESSION[username]";
// do as you like for this user type
break;
'manager':
echo "Hello User:$_SESSION[username]";
// do as you like for this user type
break;
default:
exit('You are not authorized to view this page');
break;
}
?>
0
BrianGEFF719Commented:
mukhtar2t has provided an example, however, instead of "You are not authorized to view this page", most people will redirect to the login page. eg header("Location: Login.php");

0
rdivilbissCommented:
While this titorial (
http://www.tutorialized.com/tutorial/Simple-reusable-PHP-MySQL-authentication-script/23914) covers the basics, it has XSS vulnerabilities and SQL injection vectors.

I agree the asker probably needs something basic to understand the necessary steps, but is a shame the author didn't touch on, or at least point out the potential security problems.
0
aannanAuthor Commented:
mukhtar2t,

in your script what do you mean by 'user or you can use typename instead of typeid'? and what do u mean when u refer to the control file?
0
mukhtar2tCommented:
First
I mean you can select the type name from your types table instead of typeid like this:
if(!($sql = mysql_query("select u.userid,u.username,t.typename from user u,types t where u.typeid = t.id and username = $user_name and password = $password",$conn)))
exit('Query failed');

$user_row = mysql_fetch_assoc($sql);
switch($user_row['typename'])
{
'user':
$_SESSION['user_type'] = 'user';
$_SESSION['userid'] = $user_row['userid'];
$_SESSION['username'] = $user_row['username'];
// you can add any session variable as you like.
header('location: control.php'); // or any other page
break;
'admin':
$_SESSION['user_type'] = 'admin';
$_SESSION['userid'] = $user_row['userid'];
$_SESSION['username'] = $user_row['username'];
// you can add any session variable as you like.
header('location: control.php'); // or any other page
break;
'manager':
$_SESSION['user_type'] = 'manager';
$_SESSION['userid'] = $user_row['userid'];
$_SESSION['username'] = $user_row['username'];
// you can add any session variable as you like.
header('location: control.php'); // or any other page
break;
default:
exit('You are not authorized to view this page');
break;
}

And second
There tow scripts you would create login.php and control.php
the login.php is the first page that query for the authorization and set the session variables
and the control.php is the script which the user will redirect to it after authorization succeed
0
mukhtar2tCommented:
Try it
Create three file in the same folder and save them as index.html,login.php,control.php
copy this code and past it on the index.html
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title>Login Page</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
</head>
<body>
<form method="post" action="login.php">
<table width="80%" border="0" align="center" cellpadding="0" cellspacing="0">
                <tr>
                  <td width="38%" >Username:</td>
                  <td width="62%"><input name="username" type="text" id="username" size="30"></td>
                </tr>
                <tr>
                  <td height="25">Password:</td>
                  <td><input name="password" type="password" id="password" size="30"></td>
                </tr>
                <tr>
                  <td height="30">&nbsp;</td>
                  <td>
  <input name="Submit" type="submit" value="Login">
  </td>
                </tr>
              </table>
            </form>
</body>
</html>

copy this code and past it on login.php
<?php
session_start();
if(!($conn = mysql_connect($db_server,$db_user,$db_pass)))
exit('Cannot connect to db.');
if(!mysql_select_db($db_name))
exit('Cannot select a db.');

if(!($sql = mysql_query("select userid,username,typeid from user where username = $user_name and password = $password",$conn)))
exit('Query failed');

/* I preferred using mysql_real_escape_string function instead of passing the user and pass direct to the sql string*/

$user_row = mysql_fetch_assoc($sql);
switch($user_row['typeid'])
{
1: // user or you can use typename instead of typeid
$_SESSION['user_type'] = 'user';
$_SESSION['userid'] = $user_row['userid'];
$_SESSION['username'] = $user_row['username'];
// you can add any session variable as you like.
header('location: control.php'); // or any other page
break;
2: // admin or you can use typename instead of typeid
$_SESSION['user_type'] = 'admin';
$_SESSION['userid'] = $user_row['userid'];
$_SESSION['username'] = $user_row['username'];
// you can add any session variable as you like.
header('location: control.php'); // or any other page
break;
3: // manager or you can use typename instead of typeid
$_SESSION['user_type'] = 'manager';
$_SESSION['userid'] = $user_row['userid'];
$_SESSION['username'] = $user_row['username'];
// you can add any session variable as you like.
header('location: control.php'); // or any other page
break;
default:
exit('You are not authorized to view this page');
break;
}
?>
dont forget to replace $db_user,$db_pass,$db_server,$db_name with you own db info

copy this code and past it on control.php
<?php
session_start();
switch($_SESSION['user_type'])
{
'user':
echo "Hello User:$_SESSION[username]";
// do as you like for this user type
break;
'admin':
echo "Hello User:$_SESSION[username]";
// do as you like for this user type
break;
'manager':
echo "Hello User:$_SESSION[username]";
// do as you like for this user type
break;
default:
exit('You are not authorized to view this page');
break;
}
?>

now you can open index.html on your browser and try to login with diffrent users
0
aannanAuthor Commented:
mukhtar2t,

Thanks for ur input. I implemented the code as you said but i am having some problems. It seems that I have having a problem with the mysql query. becos when i run this script I get a blank page. I put an message to display after the query and does not display so I am assuming it the query. please look at the code below, maybe I am missing something. Thanks

=======================================

<?php

session_start();

$mysql_Server = "mydbserver.connect.org";
$mysql_User= "mysql";
$mysql_Password = "";
$mysql_Database = "test";


if(!($conn = mysql_connect($mysql_Server,$mysql_User, $mysql_Password)))
exit('Cannot connect to db.');

if(!mysql_select_db($mysql_Database))
exit('Cannot select a db.');


if(!($sql = mysql_query("SELECT Employee.EmployeeID, Employee.LastName, Employee.EmployeeNum, UserType.Usertype FROM Employee, UserType
WHERE Employee.TypeID = UserType.TypeID AND Employee.LastName = $LastName AND Employee.EmployeeNum = $EmployeeNum" $conn)))
exit('Query failed');


echo "I am here";
/*


$user_row = mysql_fetch_assoc($sql);
switch($user_row['Usertype'])
{
'Employee':
$_SESSION['Usertype'] = 'Employee';
$_SESSION['EmployeeID'] = $user_row['EmployeeID'];
$_SESSION['LastName'] = $user_row['LastName'];
// you can add any session variable as you like.
header('location: employeepage.php'); // or any other page
break;

'Coordinator':
$_SESSION['Usertype'] = 'Coordinator';
$_SESSION['EmployeeID'] = $user_row['EmployeeID'];
$_SESSION['LastName'] = $user_row['LastName'];

// you can add any session variable as you like.
header('location: coordinatorpage.php'); // or any other page
break;

'Administrator':
$_SESSION['Usertype'] = 'Administrator';
$_SESSION['EmployeeID'] = $user_row['EmployeeID'];
$_SESSION['LastName'] = $user_row['LastName'];
echo " This is the adminpage";
// you can add any session variable as you like.
header('location: adminpage.php'); // or any other page
break;
default:
exit('You are not authorized to view this page');
break;
}
*/
?>
0
mukhtar2tCommented:
First there is  a comm missed
if(!($sql = mysql_query("SELECT Employee.EmployeeID, Employee.LastName, Employee.EmployeeNum, UserType.Usertype FROM Employee, UserType
WHERE Employee.TypeID = UserType.TypeID AND Employee.LastName = $LastName AND Employee.EmployeeNum = $EmployeeNum", $conn)))
exit('Query failed');

Second
you can add this line on the top
error_reporting(E_ALL);
to show any possibe error
0
mukhtar2tCommented:
Also you have to extract your GET or POST variables from $_GET,$_POST or both from $_REQUEST
0
aannanAuthor Commented:
i made those changes and I am still getting that the query failed
0
aannanAuthor Commented:
I added

$LastName = $_POST['LastName'];
$EmployeeNum = $_POST['EmployeeNum'];

before the query
0
mukhtar2tCommented:
what is the error that you are getting
0
aannanAuthor Commented:
im just getting a blank screen

and if i put and echo after the query and comment out the rest of the script, says the query failed.
0
mukhtar2tCommented:
type this line at the beginnig of your script
error_reporting(E_ALL);

and also type
echo $sql;
before mysql_query and copy/clean/post the result
i think it is failed because you did not quate the string variables like lastname
0
aannanAuthor Commented:
thanks, i finally got the query to work.. i was missing the qoutes on the string variables :)

I am also able to user the header function to forward to the various pages which works fine. But when I type in the url for example adminpage.php, it goes there without any authentication. how do i prevent that from happening i.e even if the person types in the url, they will have to authenticate before getting access to that page. Thanks
0
mukhtar2tCommented:
On the top of the adminpage type:
session_start();
if($_SESSION['Usertype'] != 'Administrator')
  header('location: login.php');
0

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
aannanAuthor Commented:
thanks mukhtar2t for your help

maybe you can help me here: http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/Q_22499080.html

Thanks
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.