Solved

user login

Posted on 2007-03-29
15
166 Views
Last Modified: 2016-08-29
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
0
Comment
Question by:CalmSoul
  • 7
  • 5
  • 3
15 Comments
 
LVL 14

Expert Comment

by:raja_ind82
Comment Utility
<?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
 
LVL 4

Expert Comment

by:secondv
Comment Utility
<?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
 
LVL 4

Expert Comment

by:secondv
Comment Utility
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
 
LVL 5

Author Comment

by:CalmSoul
Comment Utility
secondv:

where is redirects to?
0
 
LVL 4

Expert Comment

by:secondv
Comment Utility
This file is  login.php, upon successful login it redirects to  index.php. You could edit it to redirect elsewhere.
0
 
LVL 5

Author Comment

by:CalmSoul
Comment Utility
when I login it come back to the login page

any ideas?

0
 
LVL 14

Expert Comment

by:raja_ind82
Comment Utility
did you check my code? create the table "users" not "admin_users". i hope that will work for you.
0
What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

 
LVL 5

Author Comment

by:CalmSoul
Comment Utility
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
 
LVL 4

Expert Comment

by:secondv
Comment Utility
session_start(); must come before whitespace / output.
0
 
LVL 5

Author Comment

by:CalmSoul
Comment Utility
like this

<?php

session_start();

?>
0
 
LVL 5

Author Comment

by:CalmSoul
Comment Utility
Raja,

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

thanks
0
 
LVL 4

Expert Comment

by:secondv
Comment Utility
<?php

session_start();

// rest of your code

?>
0
 
LVL 5

Author Comment

by:CalmSoul
Comment Utility
secondv:

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

not sure whats happening?
0
 
LVL 14

Accepted Solution

by:
raja_ind82 earned 500 total points
Comment Utility
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
 
LVL 5

Author Comment

by:CalmSoul
Comment Utility
thanks raja I will look into these
0

Featured Post

How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

Join & Write a Comment

Suggested Solutions

This article will explain how to display the first page of your Microsoft Word documents (e.g. .doc, .docx, etc...) as images in a web page programatically. I have scoured the web on a way to do this unsuccessfully. The goal is to produce something …
Things That Drive Us Nuts Have you noticed the use of the reCaptcha feature at EE and other web sites?  It wants you to read and retype something that looks like this.Insanity!  It's not EE's fault - that's just the way reCaptcha works.  But it is …
Explain concepts important to validation of email addresses with regular expressions. Applies to most languages/tools that uses regular expressions. Consider email address RFCs: Look at HTML5 form input element (with type=email) regex pattern: T…
The viewer will learn how to count occurrences of each item in an array.

771 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

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now