Jump to content

Recommended Posts

hey guys

 

i have to following code

 

<?php
include("users/index.php");
?>

<?php
$LOGIN_INFORMATION = array(

$user_login_username => $user_login_password,

);
?>

 

the script connects to the database and fetches the data

 

the problem im having is the table has 3 tables

 

"ID" - "user_login_username" - "user_login_password"

 

in those tables are 2 entries

 

"1" - "test" - "user"

"2" - "test1" - "user1"

 

now on the login screen when i enter the username and password "test1" and "user1" it logs me in fine and works how i want it to

but when i enter "test" and "user"

it doesnt work

 

if i add another entry so the table shows

 

"1" - "test" - "user"

"2" - "test1" - "user1"

"3" - "test2" - "user2"

 

and i try the to login again with "test" and "user" it fails and so does "test1" and "user1" but "test2" and "user2" works

 

the script is only fetching the last entry from the DB

is there anyway to login with any user in the DB??

 

if this dont make sense or you need more info please ask

 

Thanks

Link to comment
https://forums.phpfreaks.com/topic/236749-help-with-9-lines-of-code/
Share on other sites

here is "connect.php"

<?php
$hostname='localhost'; //// specify host, i.e. 'localhost'
$user='********'; //// specify username
$pass='********'; //// specify password
$dbase='********'; //// specify database name
$connection = mysql_connect("$hostname" , "$user" , "$pass") 
or die ("Can't connect to MySQL");
$db = mysql_select_db($dbase , $connection) or die ("Can't select database.");
?>

 

and here is the other part "index.php" found in "users/index.php"

 

<?php
include("connect.php");

$query = "SELECT * FROM user ";
$result = mysql_query($query);
$num = mysql_num_rows ($result);
mysql_close();

if ($num > 0 ) {
$i=0;
while ($i < $num) {
$user_login_username = mysql_result($result,$i,"user_login_username");
$user_login_password = mysql_result($result,$i,"user_login_password");
$id = mysql_result($result,$i,"id");

++$i; } } else { echo "The database is empty"; }?>

 

if there is anything else just ask

Is this your code for logging in a user?

<?php
include("connect.php");

$query = "SELECT * FROM user ";
$result = mysql_query($query);
$num = mysql_num_rows ($result);
mysql_close();

if ($num > 0 ) {
$i=0;
while ($i < $num) {
$user_login_username = mysql_result($result,$i,"user_login_username");
$user_login_password = mysql_result($result,$i,"user_login_password");
$id = mysql_result($result,$i,"id");

++$i; } } else { echo "The database is empty"; }?>

If it is that is not the correct way to go about logging in users.

 

You should instead be performing a query like

SELECT username, password FROM users_table WHERE username='$username_entered' AND password='$password_entered'

You should then check to see if the query returned a match (mysql_num_rows). If it returned a match log the user in. If no match was returned the user entered invalid login credentials.

 

the original code went like this and wasnt based on mysql it was done with cookies

 

so the code went like this

<?php
$LOGIN_INFORMATION = array(
  'test' => 'testpass',
  'admin' => 'passwd'
);
?>

i have added the include and the $$ parts and so far it works how it should BUT its only working off the last entry in the DB

this is only a simple login form that i INCLUDE

i never used to connect to a DB or anything it used to use the above array and ask to login and you had to enter one of those to be able to gain access

 

here is the code to help you understand

PLEASE NOTE: if you can change the code below to connect to the DB and be able to login ect please do soo

 

<?php
/*
$LOGIN_INFORMATION = array(
  'test' => 'testpass',
  'admin' => 'passwd'
);

<?php
include("password_protect.php");
?>

logout link
http://www.example.com/path/to/protected/page.php?logout=1
*/

##################################################################
#  SETTINGS START
##################################################################

// Add login/password pairs below, like described above
$LOGIN_INFORMATION = array(
  'test' => 'testpass',
  'admin' => 'passwd'
);
// NOTE: all rows except last must have comma "," at the end of line

// request login? true - show login and password boxes, false - password box only
define('USE_USERNAME', true);

// User will be redirected to this page after logout
define('LOGOUT_URL', '/');

// time out after NN seconds of inactivity. Set to 0 to not timeout
define('TIMEOUT_MINUTES', 1800);

// 1m = 60
// 5m = 300
// 10m = 600
// 15m = 900
// 20m = 1200
// 30m = 1800
// 60m = 3600


// This parameter is only useful when TIMEOUT_MINUTES is not zero
// true - timeout time from last activity, false - timeout time from login
define('TIMEOUT_CHECK_ACTIVITY', true);

##################################################################
#  SETTINGS END
##################################################################


///////////////////////////////////////////////////////
// do not change code below
///////////////////////////////////////////////////////


// timeout in seconds
$timeout = (TIMEOUT_MINUTES == 0 ? 0 : time() + TIMEOUT_MINUTES );

// logout?
if(isset($_GET['logout'])) {
  setcookie("verify", '', $timeout, '/'); // clear password;
  header('Location: ' . LOGOUT_URL);
  exit();
}

if(!function_exists('showLoginPasswordProtect')) {

// show login form
function showLoginPasswordProtect($error_msg) {
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><head>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="robots" content="noindex, nofollow">
<title>login</title>
<link rel="stylesheet" href="index_files/style_optimized.css" type="text/css">
<!--[if IE]>
<style type="text/css">
#mid{
height:300px;
}
</style>
<![endif]-->
<meta name="robots" content="noindex, nofollow">
</head><body>
<div id="wrap">
<div id="top"></div>
<div id="mid" style="height:auto">
	<div id="content-wrap" align="center"> 

<form method="post">
    <table class="login" cellpadding="0" cellspacing="0" width="200px">
        <tbody><tr>
            <td colspan="2" align="left"><strong><font size="+1">Login</font></strong></td>
        </tr>
        <tr>
            <td class="login_lines">Username </td>
            <td class="login_lines"><input type="text" name="access_login" /><br /></td>
        </tr>
        <tr class="row2">
            <td class="login_lines">Password </td>
            <td class="login_lines"><input type="password" name="access_password" /></td>
        </tr>
        <tr>
            <td colspan="2" style="text-align: center;"><input value="Login" class="input-button" tabindex="3" type="submit"></td>
        </tr>
    </tbody></table>
</form><br />

<script type="text/javascript">
//<![CDATA[
   document.getElementById("user").focus();
//]]>
</script>
<br><br></div>
</div>
<div id="bot">
</div>

</div>
</body></html>
<?php
  // stop at this point
  die();

}
}

// user provided password
if (isset($_POST['access_password'])) {

  $login = isset($_POST['access_login']) ? $_POST['access_login'] : '';
  $pass = $_POST['access_password'];
  if (!USE_USERNAME && !in_array($pass, $LOGIN_INFORMATION)
  || (USE_USERNAME && ( !array_key_exists($login, $LOGIN_INFORMATION) || $LOGIN_INFORMATION[$login] != $pass ) ) 
  ) {
    showLoginPasswordProtect("Incorrect password.");
  }
  else {
    // set cookie if password was validated
    setcookie("verify", ($login.'%'.$pass), $timeout, '/');
    
    // Some programs (like Form1 Bilder) check $_POST array to see if parameters passed
    // So need to clear password protector variables
    unset($_POST['access_login']);
    unset($_POST['access_password']);
    unset($_POST['Submit']);
  }

}

else {

  // check if password cookie is set
  if (!isset($_COOKIE['verify'])) {
    showLoginPasswordProtect("");
  }

  // check if cookie is good
  $found = false;
  foreach($LOGIN_INFORMATION as $key=>$val) {
    $lp = (USE_USERNAME ? $key : '') .'%'.$val;
    if ($_COOKIE['verify'] == ($lp)) {
      $found = true;
      // prolong timeout
      if (TIMEOUT_CHECK_ACTIVITY) {
        setcookie("verify", ($lp), $timeout, '/');
      }
      break;
    }
  }
  if (!$found) {
    showLoginPasswordProtect("");
  }

}

?>

This is the basic code you'll need to authenticate a user from a database

if(isset($_POST['Submit']))
{
    $username = mysql_real_escape_string($_POST['access_login']);
    $password = mysql_real_escape_string($_POST['access_password']);

    $query = "SELECT user_login_username, user_login_password FROM user WHERE  user_login_username = '$username', user_login_password = '$username'";
    $result = mysql_query($query);

    // check that the query executed
    if($result)
    {
        // check that the query returned a result.
        if(mysql_num_rows($result) == 1)
        {
            // user entered correct username/password credentials
            // consider them logged in
            $_SESSION['isLoggedIn'] = true;
            $_SESSION['username']   = $username;
        }
        // No results was returned. Display error message
        else
        {
            echo "Sorry the username/password you entered is incorrect";
        }
    }
    // query failed for some reason, probably due to an error lets see why
    else
    {
        die('MySQL Error: ' . mysql_error() . '<br />Query: ' . $query);
    }
}

 

That code should be enough. However when dealing with passwords you should be storing them in their encrypted form rather than as plain text. The most popular are MD5 or SHA1 hashes. If you decide to store the users passwords in encrypted form you'll need to modify the code so it compares the passwords in their encrypted form rather than plain text. If the passwords are stored in the database as md5 hases then you'll chang the following line

    $password = mysql_real_escape_string($_POST['access_password']);

to

    $password = md5($_POST['access_password']);

Now query will compare the hashes.

 

Now to check if a user is logged in you'd use the following code in any page that requires the user to be logged in.

<?php
session_start();
if(!isset(_SESSION['isLoggedIn']) || (isset($_SESSION['isLoggedIn']) && $_SESSION['isLoggedIn'] != true))
{
     header('Location login.php');
}
?>

im not fussed on authenticating ect the website is on a local network and not open to the WWW

 

the code is so a select few of the users can access other area's but im wanting this to run off a DB

 

if someone could edit / change the code below to allow it to GET the data from the database that would be great

im not bothered about a registration page or anything i just want the code below to connect to the DB so it can login the right user if that makes sense...

 

<?php
/*
$LOGIN_INFORMATION = array(
  'test' => 'testpass',
  'admin' => 'passwd'
);

<?php
include("password_protect.php");
?>

logout link
http://www.example.com/path/to/protected/page.php?logout=1
*/

##################################################################
#  SETTINGS START
##################################################################

// Add login/password pairs below, like described above
$LOGIN_INFORMATION = array(
  'test' => 'testpass',
  'admin' => 'passwd'
);
// NOTE: all rows except last must have comma "," at the end of line

// request login? true - show login and password boxes, false - password box only
define('USE_USERNAME', true);

// User will be redirected to this page after logout
define('LOGOUT_URL', '/');

// time out after NN seconds of inactivity. Set to 0 to not timeout
define('TIMEOUT_MINUTES', 1800);

// 1m = 60
// 5m = 300
// 10m = 600
// 15m = 900
// 20m = 1200
// 30m = 1800
// 60m = 3600


// This parameter is only useful when TIMEOUT_MINUTES is not zero
// true - timeout time from last activity, false - timeout time from login
define('TIMEOUT_CHECK_ACTIVITY', true);

##################################################################
#  SETTINGS END
##################################################################


///////////////////////////////////////////////////////
// do not change code below
///////////////////////////////////////////////////////


// timeout in seconds
$timeout = (TIMEOUT_MINUTES == 0 ? 0 : time() + TIMEOUT_MINUTES );

// logout?
if(isset($_GET['logout'])) {
  setcookie("verify", '', $timeout, '/'); // clear password;
  header('Location: ' . LOGOUT_URL);
  exit();
}

if(!function_exists('showLoginPasswordProtect')) {

// show login form
function showLoginPasswordProtect($error_msg) {
?>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"><head>
<link rel="shortcut icon" href="favicon.ico" type="image/x-icon"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><meta name="robots" content="noindex, nofollow">
<title>login</title>
<link rel="stylesheet" href="index_files/style_optimized.css" type="text/css">
<!--[if IE]>
<style type="text/css">
#mid{



height:300px;
}
</style>
<![endif]-->
<meta name="robots" content="noindex, nofollow">
</head><body>
<div id="wrap">



<div id="top"></div>



<div id="mid" style="height:auto">





<div id="content-wrap" align="center"> 

<form method="post">
    <table class="login" cellpadding="0" cellspacing="0" width="200px">
        <tbody><tr>
            <td colspan="2" align="left"><strong><font size="+1">Login</font></strong></td>
        </tr>
        <tr>
            <td class="login_lines">Username </td>
            <td class="login_lines"><input type="text" name="access_login" /><br /></td>
        </tr>
        <tr class="row2">
            <td class="login_lines">Password </td>
            <td class="login_lines"><input type="password" name="access_password" /></td>
        </tr>
        <tr>
            <td colspan="2" style="text-align: center;"><input value="Login" class="input-button" tabindex="3" type="submit"></td>
        </tr>
    </tbody></table>
</form><br />

<script type="text/javascript">
//<![CDATA[
   document.getElementById("user").focus();
//]]>
</script>
<br><br></div>
</div>
<div id="bot">
</div>

</div>
</body></html>
<?php
  // stop at this point
  die();

}
}

// user provided password
if (isset($_POST['access_password'])) {

  $login = isset($_POST['access_login']) ? $_POST['access_login'] : '';
  $pass = $_POST['access_password'];
  if (!USE_USERNAME && !in_array($pass, $LOGIN_INFORMATION)
  || (USE_USERNAME && ( !array_key_exists($login, $LOGIN_INFORMATION) || $LOGIN_INFORMATION[$login] != $pass ) ) 
  ) {
    showLoginPasswordProtect("Incorrect password.");
  }
  else {
    // set cookie if password was validated
    setcookie("verify", ($login.'%'.$pass), $timeout, '/');
    
    // Some programs (like Form1 Bilder) check $_POST array to see if parameters passed
    // So need to clear password protector variables
    unset($_POST['access_login']);
    unset($_POST['access_password']);
    unset($_POST['Submit']);
  }

}

else {

  // check if password cookie is set
  if (!isset($_COOKIE['verify'])) {
    showLoginPasswordProtect("");
  }

  // check if cookie is good
  $found = false;
  foreach($LOGIN_INFORMATION as $key=>$val) {
    $lp = (USE_USERNAME ? $key : '') .'%'.$val;
    if ($_COOKIE['verify'] == ($lp)) {
      $found = true;
      // prolong timeout
      if (TIMEOUT_CHECK_ACTIVITY) {
        setcookie("verify", ($lp), $timeout, '/');
      }
      break;
    }
  }
  if (!$found) {
    showLoginPasswordProtect("");
  }

}

?>

 

The basic code I gave you does what you want, you need to modify it slightly so it works with your existing code. I'm not going to do this for you. If you want someone else to modify your existing code you need to post in freelance board.

The basic code I gave you does what you want, you need to modify it slightly so it works with your existing code. I'm not going to do this for you. If you want someone else to modify your existing code you need to post in freelance board.

 

ok thanks ill have a go at this

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.