user login

I am looking for a simple user login php script

user enter user name and password... script check the database

and then allow access...

also need ability to protect pages already created

thanks
LVL 5
CalmSoulAsked:
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.

raja_ind82Commented:
<?php
$conn = mysql_connect("localhost", "root", "");
mysql_select_db("iml_pda_remote");
if(isset($_POST['submitlogin']))
{
      $username=$_POST['username'];
      $password=$_POST['password'];
      $query="SELECT * FROM users WHERE user_name='$username' AND user_pass='$password'";      
      $result=mysql_query($query);
      if(mysql_num_rows($result)>0)
      {
            $row=mysql_fetch_array($result);                  
            $_SESSION['session_user']=$row['admin_id'];      
      }
      else
            $error_message="Password Ircorrect";
}
if(isset($_SESSION['session_user']))
{
      header("Location: index.php");
      exit();
}
else
{
?>
<HTML>
<HEAD>
                                     
<TITLE> <?PHP echo  (isset($_SESSION['session_user'])? " - Home":" - Login Page" );      ?>        </TITLE>
<script>
      function index_validate()
{
with(document.login_form)
      {
      if(username.value=="")
            {
            alert("Enter user name");
            username.focus();
            return false;
            }
      if(password.value=="")
            {
            alert("Enter password");
            password.focus();
            return false;
            }
      }

}
</script>
</HEAD>
<TABLE BORDER=0 CELLSPACING=0 CELLPADDING=0 WIDTH="100%" HEIGHT="100%">

      <TR HEIGHT="77%">
            <TD WIDTH="1%" >&nbsp;</TD>
 
            <TD  WIDTH="77%" VALIGN="top" width="40%" ALIGN="center">
                  <TABLE CELLSPACING="0" CELLPADDING="0" ALIGN="center"  WIDTH="40%">
                        <TR><TD COLSPAN=3 STYLE="height:2px" BGCOLOR="#463EAC"></TD></TR>
                        <TR>
                              <TD STYLE="width:2px"  BGCOLOR="#463EAC"></TD>
                              <TD BGCOLOR="#F8F9FB" ALIGN="center">
                                     <FORM NAME="login_form" METHOD="post" ACTION="login.php">
                                     <TABLE CELLSPACING=10 CELLPADDING=0 BORDER=0 ALIGN="center"  width="80%">
                                     <?php
      if($error_message!="")
      {
      ?>
                                          <TR>
                                                <TD COLSPAN="2" ALIGN="center" CLASS="error_message">                                                      
                                                <?php echo $error_message?>
                                                </TD>
                                          </TR>
                              <?php }

                                    if($success_message!="")
      {
      ?>

                                          <TR>
                                                <TD COLSPAN="2" ALIGN="center" CLASS="success_message">                                                      
                                                <?php echo $success_message?>
                                                </TD>
                                          </TR>
                                                                        <?php }?>
                                           <TR>
                                                      <TD ALIGN="left" CLASS="heading" colspan="2">
                                                      
                                                </a><b>
                                                      User Login</b>
                                                </TD>
                                          </TR>
                                          <TR>
                                                <TD width="50%"      CLASS="caption">User Name</TD>
                                                <TD width="50%" >
                                                      <INPUT TYPE="text" NAME="username" CLASS="textbox">
                                                      <SCRIPT>document.login_form.username.focus()</SCRIPT>
                                                </TD>
                                          </TR>
                                          <TR>
                                                <TD CLASS="caption">
                                                      Password
                                                </TD>
                                                <TD>
                                                      <INPUT TYPE="password" Name="password" CLASS="textbox">
                                                </TD>
                                                </TR>
                                          <TR>
                                                <TD>&nbsp;</TD>
                                                <TD><INPUT TYPE="submit" VALUE="Login" NAME="submitlogin" CLASS="smallbutton" ONCLICK="return index_validate()">&nbsp; &nbsp;<INPUT TYPE="reset" CLASS="smallbutton"></TD>
                                          </TR>
                                          <TR>
                                                <TD COLSPAN="2">
                                                &nbsp;                                                      
                                                </TD>
                                          </TR>
                                    </TABLE>
                                    </FORM>
                              </TD>
                              <TD BGCOLOR="#463EAC" STYLE="width:2px"></TD>
                        </TR>
                        <TR><TD COLSPAN=3  STYLE="height:2px" BGCOLOR="#463EAC"></TD></TR>
                  </TABLE>
                                           <?php
                                           }
                                           ?>
            </TD>
      </TR>

</TABLE>


CREATE TABLE `admin_users` (
  `admin_id` int(11) NOT NULL auto_increment,
  `user_name` varchar(20) default NULL,
  `user_pass` varchar(20) default NULL,
  `user_status` varchar(11) default NULL,
  PRIMARY KEY  (`admin_id`)
)

Regards,
M.Raja
0
secondvCommented:
<?php

$db =& mysql_connect('localhost', '', '') or die(mysql_error());
mysql_select_db('database') or die(mysql_error());

session_start();

if (isset($_SESSION['userid'], $_SESSION['username'], $_SESSION['key']) AND $_SESSION['key'] == substr(strrev(md5($_SERVER['REMOTE_ADDR'])), 0, 16))
{
      header('Location: index.php');
      exit;
}

$error = '';

if (!empty($_POST['submit']))
{
      $username = trim(strip_tags(stripslashes($_POST['username'])));
      $password = trim(strip_tags(stripslashes($_POST['password'])));

      if (empty($username))
      {
            die('You must enter a username. &laquo; <a href="javascript:history.back(-1);">Back</a>');
      }

      if (empty($password))
      {
            die('You must enter a username. &laquo; <a href="javascript:history.back(-1);">Back</a>');
      }

      $user = mysql_query("
            SELECT userid
            FROM users
            WHERE username='" . mysql_escape_string($username) . "'
                  AND password='" . md5($password) . "'
      ") or die(mysql_error());

      $user = mysql_fetch_assoc($check);

      if (count($user) > 0)
      {
            $_SESSION['userid'] = $user['userid'];
            $_SESSION['username'] = $username;
            $_SESSION['key'] = substr(strrev(md5($_SERVER['REMOTE_ADDR'])), 0, 16);
            header('Location: index.php');
            exit;
      }
      else
      {
            die('Incorrect username/password. &laquo; <a href="javascript:history.back(-1);">Back</a>');
      }
}

?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
      "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<title>User Login</title>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<meta http-equiv="Content-Language" content="en-us" />
<script language="JavaScript">
function validateForm(myForm)
{
      if (myForm.username.value == '' OR myForm.username.value == NULL)
      {
            alert('Please enter your username.');
            myForm.username.focus();
            return false;
      }

      if (myForm.password.value == '' OR myForm.password.value == NULL)
      {
            alert('Please enter your password.');
            myForm.password.focus();
            return false;
      }
      return true;
}
</script>
</head>

<body>

<form method="post" action="login.php" onsubmit="return validateForm(this);">
<table border="0" width="100%" cellspacing="0" cellpadding="0">
<caption>User Login</caption>
<tbody>
<tr>
      <td>Username:</td>
      <td><input type="text" name="username" id="username" /></td>
</tr>
<tr>
      <td>Password:</td>
      <td><input type="password" name="password" id="password" /></td>
</tr>
<tr>
      <td colspan="2" align="center"><input type="submit" name="submit" id="submit" value="Login" /></td>
</tr>
</tbody>
</table>
</form>

</body>
</html>

Then on each page you want to check to see if they are logged in, at the top, right after:

<?php

Add:

session_start();

Then your includes if you have any (like if you have a config file you'll use for mysql connections etc, then add:

if (!isset($_SESSION['userid'], $_SESSION['username'], $_SESSION['key']) OR $_SESSION['key'] != substr(strrev(md5($_SERVER['REMOTE_ADDR'])), 0, 16))
{
      header('Location: login.php');
      exit;
}


And here is an example mysql table, being used for this code:

CREATE TABLE `users` (
      `userid` INT UNSIGNED NOT NULL AUTO_INCREMENT,
      `username` VARCHAR(100) NOT NULL,
      `password` CHAR(32) NOT NULL,
      PRIMARY KEY (`userid`)
);


When adding users to the database, be sure their passwords are md5'ed.
0
secondvCommented:
Just noticed an error in what I posted above, instead of posting it all again.. change:

      $user = mysql_fetch_assoc($check);

to

      $user = mysql_fetch_assoc($user);
0
Cloud Class® Course: Python 3 Fundamentals

This course will teach participants about installing and configuring Python, syntax, importing, statements, types, strings, booleans, files, lists, tuples, comprehensions, functions, and classes.

CalmSoulAuthor Commented:
secondv:

where is redirects to?
0
secondvCommented:
This file is  login.php, upon successful login it redirects to  index.php. You could edit it to redirect elsewhere.
0
CalmSoulAuthor Commented:
when I login it come back to the login page

any ideas?

0
raja_ind82Commented:
did you check my code? create the table "users" not "admin_users". i hope that will work for you.
0
CalmSoulAuthor Commented:
I added "session_start()" getting following error...
Warning: session_start() [function.session-start]: Cannot send session cache limiter - headers already sent (output started at /home/geocom/public_html/rdb/CompleteRecords.php:8) in /home/geocom/public_html/rdb/CompleteRecords.php on line 44
0
secondvCommented:
session_start(); must come before whitespace / output.
0
CalmSoulAuthor Commented:
like this

<?php

session_start();

?>
0
CalmSoulAuthor Commented:
Raja,

How to protect pages? can you uploading these files in the zip format?

thanks
0
secondvCommented:
<?php

session_start();

// rest of your code

?>
0
CalmSoulAuthor Commented:
secondv:

your code is redirecting to index.php... even if the login fails...

not sure whats happening?
0
raja_ind82Commented:
CalmSoul,

To download the file, you must be logged into EE-Stuff. Here are two pages that will display your file, if logged in:

View all files for Question ID: 22481875
https://filedb.experts-exchange.com/incoming/ee-stuff/3091-login.zip 

Direct link to your file
https://filedb.experts-exchange.com/incoming/ee-stuff/3091-login.zip 
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
CalmSoulAuthor Commented:
thanks raja I will look into these
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.