Link to home
Start Free TrialLog in
Avatar of CalmSoul
CalmSoulFlag for United States of America

asked on

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
Avatar of raja_ind82
raja_ind82
Flag of India image

<?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
<?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.
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);
Avatar of CalmSoul

ASKER

secondv:

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

any ideas?

did you check my code? create the table "users" not "admin_users". i hope that will work for you.
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
session_start(); must come before whitespace / output.
like this

<?php

session_start();

?>
Raja,

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

thanks
<?php

session_start();

// rest of your code

?>
secondv:

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

not sure whats happening?
ASKER CERTIFIED SOLUTION
Avatar of raja_ind82
raja_ind82
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
thanks raja I will look into these