Jump to content

[SOLVED] Making an external PHP login script 'inline'


alex3

Recommended Posts

Hi,

 

I'm currently using the below script and HTML to login users from a page called login.php. If the login  details cannot be found in the MySQL database, the user is presented with "Wrong Username or Password". What I'd ideally like to happen is that if the user enters the wrong data, the warning message is shown on the form that the details were entered in to. This prevents the need for the user to go back in their browser, of course.

 

HTML:

<form action="scripts/checklogin.php" method="post">
<div>
	<label for="username">Username:</label><br>
	<input id="username" name="username" type="text"><br>
	<label for="password">Password:</label><br>
	<input id="password" name="password" type="password">
	<input id="submit" type="submit" value="">
</div>
</form>

 

PHP:

<?php
ob_start();

// Include MySQL database details
include("../includes/db.php");

// Connect to server and select databse.
mysql_connect("$host", "$dbusername", "$dbpassword")or die("cannot connect"); 
mysql_select_db("$db_name")or die("cannot select DB");

// Define $username and $password then encrypt it
$username=$_POST['username']; 
$password=$_POST['password'];
$enc_password=md5($password);

// To protect MySQL injection
$username = stripslashes($username);
$enc_password = stripslashes($enc_password);
$username = mysql_real_escape_string($username);
$enc_password = mysql_real_escape_string($enc_password);

$sql="SELECT * FROM $tbl_name WHERE username='$username' and password='$enc_password'";
$result=mysql_query($sql);

// Mysql_num_row is counting table row
$count=mysql_num_rows($result);
// If result matched $username and $password, table row must be 1 row

if($count==1){
// Register $username, $password and redirect to file "index.php" 
// which checks for a session username
session_start();
$_SESSION['username']=$username;
$_SESSION['password']=$enc_password;
header("location:../index.php");
}
else {
echo "Wrong Username or Password";
}

ob_end_flush();
?>

 

I've no real clue on how the make this script be 'inline' with login.php or how to insert an error message in to the correct place if there is an error. I'm more provicient in jQuery than PHP; would a combination of AJAX and PHP make this easier or not? I went for the pure PHP approach first before of the ease with which MySQL is usable.

 

Cheers,

Alex

If you don't want the user to go back just set your action to this:

 

<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">

 

Then put all your code in the same page, like so:

 

if (isset($_POST['submit'])) {
  //The user clicked "submit" so do something...
  //Handle all your errors through here.
}
else {
  //The user has NOT clicked on "submit" so show the form instead
}

 

This will keep you on the same page even if the user has the wrong credentials.

<?php
session_start();

if (isset($_POST['username']) && isset($_POST['password'])) {

foreach ($_POST as $key => $value) {

	$_POST[$key] = trim(stripslashes($value));

}

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

        $username = $_POST['username'];

// Include MySQL database details
include_once '../includes/db.php';

mysql_select_db($db_name, mysql_connect($host, $dbusername, $dbpassword) or die(mysql_error()));

$sql = mysql_query("SELECT * FROM $tbl_name WHERE username='$username' and password='$enc_password'") or die(mysql_error());

$row = mysql_fetch_array($sql);

if (!$row) {

	$err = "That password and user combination does not exist";
}

else {

	$_SESSION['loggedin']['user'] = $_POST['username'];

}

}


?>

<table cellpadding='3' cellspacing='3' style='border: 1px solid #BBB;' width='100%'>

<?php 

if (!is_null($err)) {

echo "<tr><td align='center'>$err</td></tr>";
}

?>

<tr>

<td>

<form action="scripts/checklogin.php" method="post">
   <div>
      <label for="username">Username:</label><br>
      <input id="username" name="username" type="text"><br>
      <label for="password">Password:</label><br>
      <input id="password" name="password" type="password">
      <input id="submit" type="submit" value="">
   </div>
</form>

</td>

</tr>

</table>

 

I rewrote it and cleaned it up a little bit so you could see what was going on a little better.  Also, when setting a session to denote that a user is authenticated there is NEVER a good reason to store the user's password into the session ... even if it is encrypted (or in this case hashed).

Here's how I would do it

 

<?php
session_start();

// Include MySQL database details
include("../includes/db.php");

if (isset($_POST['submit'])) { //The user has clicked on the submit button
  // Define $username, $password and encrypt it
  $username = mysql_real_escape_string(stripslashes(trim($_POST['username']))); 
  $password = md5(mysql_real_escape_string(stripslashes(trim($_POST['password']))));
  
  // Connect to server and select databse.
  mysql_connect("$host", "$dbusername", "$dbpassword")or die("cannot connect"); 
  mysql_select_db("$db_name")or die("cannot select DB");
  $sql = "SELECT * FROM $tbl_name WHERE username = '$username' AND password = '$password'";
  $result = mysql_query($sql);
  
  // Mysql_num_row is counting table row
  $count = mysql_num_rows($result);
  
  // If result matched $username and $password, table row must be 1 row
  if($count == 1) {
  // Register $username, $password and redirect to file "index.php" 
  // which checks for a session username
  $_SESSION['username'] = $username;
  header('location: ../index.php');
  }
  else { //Wrong username or password, show the form again with an error message
    echo <<<HTML
    <form action="{$_SERVER['PHP_SELF']}" method="POST">
      <div>
        <label for="username">Username:</label><br>
        <input id="username" name="username" type="text" value="{$username}"><br>
        <label for="password">Password:</label><br>
        <input id="password" name="password" type="password">
        <input id="submit" name="submit" type="submit" value="">
        <br /><br />
        <b>Wrong Username or Password</b>
      </div>
    </form>
HTML;
  }

}
else { //The user has NOT clicked on the submit button
  echo <<<HTML
  <form action="{$_SERVER['PHP_SELF']}" method="POST">
    <div>
      <label for="username">Username:</label><br>
      <input id="username" name="username" type="text"><br>
      <label for="password">Password:</label><br>
      <input id="password" name="password" type="password">
      <input id="submit" name="submit" type="submit" value="">
    </div>
  </form>
HTML;
}
?>

 

If you notice I did all the sanitation in one line. In addition its a pretty long line, so I would recommend creating a function. Like so:

 

function sanitize($input, $encrypt = 'no') {
  if ($encrypt == 'yes')
    return md5(mysql_real_escape_string(stripslashes(trim($input))));
  return mysql_real_escape_string(stripslashes(trim($input)));
}

 

So then your code would need to be updated to

 

$username = sanitize($_POST['username']);
$password = sanitize($_POST['password'], yes);

 

Make sure you understand what's happening from the entire code, don't just copy and paste, otherwise, it ruins the point in learning.

Here's how I would do it

 

<?php
session_start();

// Include MySQL database details
include("../includes/db.php");

if (isset($_POST['submit'])) { //The user has clicked on the submit button
  // Define $username, $password and encrypt it
  $username = mysql_real_escape_string(stripslashes(trim($_POST['username']))); 
  $password = md5(mysql_real_escape_string(stripslashes(trim($_POST['password']))));
  
  // Connect to server and select databse.
  mysql_connect("$host", "$dbusername", "$dbpassword")or die("cannot connect"); 
  mysql_select_db("$db_name")or die("cannot select DB");
  $sql = "SELECT * FROM $tbl_name WHERE username = '$username' AND password = '$password'";
  $result = mysql_query($sql);
  
  // Mysql_num_row is counting table row
  $count = mysql_num_rows($result);
  
  // If result matched $username and $password, table row must be 1 row
  if($count == 1) {
  // Register $username, $password and redirect to file "index.php" 
  // which checks for a session username
  $_SESSION['username'] = $username;
  header('location: ../index.php');
  }
  else { //Wrong username or password, show the form again with an error message
    echo <<<HTML
    <form action="{$_SERVER['PHP_SELF']}" method="POST">
      <div>
        <label for="username">Username:</label><br>
        <input id="username" name="username" type="text" value="{$username}"><br>
        <label for="password">Password:</label><br>
        <input id="password" name="password" type="password">
        <input id="submit" name="submit" type="submit" value="">
        <br /><br />
        <b>Wrong Username or Password</b>
      </div>
    </form>
HTML;
  }

}
else { //The user has NOT clicked on the submit button
  echo <<<HTML
  <form action="{$_SERVER['PHP_SELF']}" method="POST">
    <div>
      <label for="username">Username:</label><br>
      <input id="username" name="username" type="text"><br>
      <label for="password">Password:</label><br>
      <input id="password" name="password" type="password">
      <input id="submit" name="submit" type="submit" value="">
    </div>
  </form>
HTML;
}
?>

 

If you notice I did all the sanitation in one line. In addition its a pretty long line, so I would recommend creating a function. Like so:

 

function sanitize($input, $encrypt = 'no') {
  if ($encrypt == 'yes')
    return md5(mysql_real_escape_string(stripslashes(trim($input))));
  return mysql_real_escape_string(stripslashes(trim($input)));
}

 

So then your code would need to be updated to

 

$username = sanitize($_POST['username']);
$password = sanitize($_POST['password'], yes);

 

Make sure you understand what's happening from the entire code, don't just copy and paste, otherwise, it ruins the point in learning.

 

That is a lot of extra code that really isn't needed.  There is no good reason to have to write the form twice in your code.

I've used your script phpORcaffeine and had to make a changes to get it working. Specifically, this line is changed

 

mysql_select_db($db_name, mysql_connect($host, $dbusername, $dbpassword)) or die(mysql_error());

 

from the original:

mysql_select_db($db_name, mysql_connect($host, $dbusername, $dbpassword) or die(mysql_error()));

 

The original line threw up this error

Warning:  mysql_select_db(): supplied argument is not a valid MySQL-Link resource in /home/alexpear/public_html/freshnme/login.php on line 38

No database selected

 

My remaining problems are that the script doesn't redirect to index.php because I can't change the header after the <html> tag and that the page is refreshed when the script is running. The latter is both confusing and a problem because it would look nicer if the page didn't refresh if there was an error ;) and because at the top of the login.php page I have this script

 

<?php
session_start();
if (isset($_SESSION['loggedin']['user'])){
header("location:index.php");}
?>

 

which, if the page is being loaded again after the login script has run, should redirect to index.php. This problem is more serious than the aesthetic one, of course. The session is definitely being created though, because I can access index.php (which also checks the session in a similar way).

Archived

This topic is now archived and is closed to further replies.

×
×
  • 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.