Solved

php login script and user management

Posted on 2007-03-31
21
292 Views
Last Modified: 2013-12-12
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 :)

0
Comment
Question by:aannan
  • 8
  • 8
  • 2
  • +2
21 Comments
 
LVL 28

Expert Comment

by:gamebits
ID: 18829256
<?

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
 

Author Comment

by:aannan
ID: 18829331
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
 
LVL 29

Expert Comment

by:rdivilbiss
ID: 18829395
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
Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

 
LVL 19

Expert Comment

by:BrianGEFF719
ID: 18829396
HEre is an example of how to perform authentication using mySql:

http://www.tutorialized.com/tutorial/Simple-reusable-PHP-MySQL-authentication-script/23914
0
 
LVL 4

Expert Comment

by:mukhtar2t
ID: 18829446
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
 
LVL 19

Expert Comment

by:BrianGEFF719
ID: 18829452
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
 
LVL 29

Expert Comment

by:rdivilbiss
ID: 18829479
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
 

Author Comment

by:aannan
ID: 18830470
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
 
LVL 4

Expert Comment

by:mukhtar2t
ID: 18830509
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
 
LVL 4

Expert Comment

by:mukhtar2t
ID: 18830624
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
 

Author Comment

by:aannan
ID: 18834658
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
 
LVL 4

Expert Comment

by:mukhtar2t
ID: 18834679
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
 
LVL 4

Expert Comment

by:mukhtar2t
ID: 18834866
Also you have to extract your GET or POST variables from $_GET,$_POST or both from $_REQUEST
0
 

Author Comment

by:aannan
ID: 18841247
i made those changes and I am still getting that the query failed
0
 

Author Comment

by:aannan
ID: 18841255
I added

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

before the query
0
 
LVL 4

Expert Comment

by:mukhtar2t
ID: 18841266
what is the error that you are getting
0
 

Author Comment

by:aannan
ID: 18841297
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
 
LVL 4

Expert Comment

by:mukhtar2t
ID: 18841521
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
 

Author Comment

by:aannan
ID: 18853037
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
 
LVL 4

Accepted Solution

by:
mukhtar2t earned 250 total points
ID: 18853072
On the top of the adminpage type:
session_start();
if($_SESSION['Usertype'] != 'Administrator')
  header('location: login.php');
0
 

Author Comment

by:aannan
ID: 18874232
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

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
Introduction This article is intended for those who are new to PHP error handling (https://www.experts-exchange.com/articles/11769/And-by-the-way-I-am-New-to-PHP.html).  It addresses one of the most common problems that plague beginning PHP develop…
The viewer will learn how to dynamically set the form action using jQuery.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

809 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question