Jump to content

need assistance with authenticating username and PW


webguync

Recommended Posts

Hello,

 

I have a form I created which submits data from the form into a database. Standard stuff such as firstname, lastname, username and password. What I need now is to create code that searches the database for the correct username and password that was entered and allows entry into another console area if the username/password is entered with the information they registered with, if not, take them to an errors page.

 

Here is the code that submits the initial information into the database

 


<?php

//set up database and table names
$db_name ="shadowdata";
$table_name ="RegistrationForm";


//connect to MySQL and select database to use
$connection = @mysql_connect("localhost","username","PW") or die(mysql_error());

$db = @mysql_select_db($db_name,$connection) or die(mysql_error());

//create SQL statement and issue query
$sql = "INSERT INTO $table_name (fname, lname, zip, loginemail, loginpw, phone, date_submitted) VALUES ('$_POST[fname]', '$_POST[lname]', '$_POST[zip]', '$_POST[loginemail]', '$_POST[loginpw]', '$_POST[phone]', now())";
$result = @mysql_query($sql,$connection)or die(mysql_error());
/* E-mail stuff here */
$my_email = "[email protected]";
$bcc = "";
$subject = "Comments from contact form";
$message = "You received a mesage from {$_POST['loginemail']}"; //populate as you see fit from data from the form
mail($my_email, $subject, $message);

A simple example.

 

<?php

  if (isset($_POST['submit'])) {
    
    // connect to db.
    
    $uname = mysql_real_escape_string($_POST['uname']);
    $upass = mysql_real_escape_string($_POST['upass']);

    $sql = "SELECT uname,upass FROM users WHERE uname = '$uname' && upass = '$upass'";
    if ($result = mysql_query($sql)) {
      if (mysql_num_rows($result)) {
        session_start();
        $_SESSION['logged'] = true;
        header("Location: secretpage.php");
      } else {
        header("Location: loginfailed.php");
      }
    }
  }

?>

does this look right? For some reason the result is a blank white page. I am not sure where the error is occurring.

 


<?php
if (isset($_POST['submit'])) {

//connect to MySQL and select database to use
$connection = @mysql_connect("localhost","username","PW") or die(mysql_error());
$db = @mysql_select_db($db_name,$connection) or die(mysql_error());

$username = mysql_real_escape_string($_POST['loginemail']);
$userpw = mysql_real_escape_string($_POST['loginpw']);

$sql = "SELECT loginemail,loginpw FROM RegistrationForm WHERE loginemail = '$username' && loginpw = '$userpw'";

if ($result = mysql_query($sql)) {

if (mysql_num_rows($result)) {
session_start();
$_SESSION['logged'] = true;
header("Location: console.php");
} else {
        header("Location: index.php?error=x");
      }
    }
  }


?>


This is one of my old login/register scripts, could easily be edited...

 

Register.php

 

<?php
require("connections/db.php");

function createRandomPassword() {
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$i = 0;
$pass = '' ;

while ($i <= 7){
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$pass = $pass . $tmp;
$i++;
}
return $pass;
}

$ip = $_SERVER['REMOTE_ADDR'];

$sub = htmlspecialchars($_POST['submit']);
$login = $_POST['loginname'];
$user = mysql_real_escape_string($_POST['username']);
$email = mysql_real_escape_string($_POST['email']);
$rep = mysql_real_escape_string($_POST['email_rep']);
$gender = mysql_real_escape_string($_POST['gender']);

if ($sub){

if ( empty($login) ){
$errormsg = "Please enter your desired login-name in the \"Login-name\" field";
}else{

if ( empty($user) ){
$errormsg = "Please enter your desired username in the \"Username\" field.";
}else{

if ( empty($email) ){
$errormsg = "Please enter your email address in the \"Email\" field.";
}else{

if ( empty($rep) ){
$errormsg = "Please repeat your email in the \"Repeat email\" field.";
}else{

if ( !ctype_alnum($login) ){
$errormsg = "Login-name's can only contain alpha-numeric characters.";
}else{

if ( !ctype_alnum($user) ){
$errormsg = "Username's can only contain alpha-numeric characters.";
}else{

if ( strlen($login) < 3 || strlen($login) > 20 ){
$errormsg = "Login-name's have a character limit of 3-20 characters.";
}else{

if ( strlen($user) < 3 || strlen($user) > 20 ){
$errormsg = "Username's have a character limit of 3-20 characters.";
}else{

if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
$errormsg = "The email you have entered is not a valid email format.";
}else{

if ( $email != $rep ){
$errormsg = "The email addresses you have entered do not match.";
}else{

if ( ($gender != "Unknown") && ($gender != "Male") && ($gender != "Female")  ){
$errormsg = "Tampering with post-data...?";
}else{

$loginname = md5($login);

$query_string = "SELECT id FROM accounts WHERE loginname = '$loginname' LIMIT 1";
$query = mysql_query($query_string)or die(mysql_error());
$numrows = mysql_numrows($query);

if ( $numrows != 0 ){
$errormsg = "The login-name you have chosen is already in use.";
}else{

$query_string1 = "SELECT id FROM accounts WHERE username = '$user' LIMIT 1";
$query1 = mysql_query($query_string1)or die(mysql_error());
$numrows1 = mysql_numrows($query1);

if ( $numrows1 != 0 ){
$errormsg = "The username you have chosen is already in use.";
}else{

$query_string2 = "SELECT id FROM accounts WHERE email = '$email' AND status = 'Alive' ORDER BY id DESC";
$query2 = mysql_query($query_string2)or die(mysql_error());
$numrows2 = mysql_numrows($query2);

if ( $numrows2 != 0 ){
$errormsg = "That email is in use by a living account.";
}else{

$pass = createRandomPassword();
$password = md5($pass);

$insert_string = "INSERT INTO accounts ( id , loginname , username , password , email , ip , activity , status , gender )
VALUES
( '' , '$loginname' , '$user' , '$password' , '$email' , '$ip' , '' , 'Alive' , '$gender' )";

mysql_query($insert_string)or die(mysql_error());

$to = "".$user." <".$email.">";
$subject = "Subject";
$message = "Thank you for registering at SiteName, your login details are as follows:
<br />
<br />
Login-name: ".$login."
<br />
Password: ".$pass."
<br />
<br />
You can now login at: <a href=\"http://url.com\">SiteName</a>
<br />
<br />
[email protected]
<br />";
$headers = "From: [email protected]\r\n" .
       'X-Mailer: PHP/' . phpversion() . "\r\n" .
       "MIME-Version: 1.0\r\n" .
       "Content-Type: text/html; charset=utf-8\r\n" .
       "Content-Transfer-Encoding: &#173; 8bit\r\n\r\n";

mail ($to, $subject, $message, $headers);

$successmsg = "You have successfully registered to SiteName - your login details have been emailed to you. Please remember to check your junk/spam folder.";

}}}}}}}}}}}}}}}

mysql_close();
?>

 

Login.php

 

<?php
session_start();
require("connections/db.php");

if ( !empty($_SESSION['username']) ){
Header("Location: ???.php");
}

$sub = htmlspecialchars($_POST['submit']);
$user = $_POST['loginname'];
$pass = $_POST['password'];

if ($sub){

if ( empty($user) ){
$errormsg = "Please enter your login name in the \"Login-name\" field.";
}else{

if  ( empty($pass) ){
$errormsg = "Please enter your password in the \"Password\" field.";
}else{

if ( strlen($user) < 3 || strlen($user) > 20 ){
$errormsg = "Login name's have a character limit of 3-20 characters.";
}else{

if ( strlen($pass) < 5 || strlen($pass) > 20 ){
$errormsg = "Password's have a character limit of 5-20 characters.";
}else{

if ( !ctype_alnum($user) ){
$errormsg = "Login name's can only contain alpha-numeric characters.";
}else{

$user = md5($user);
$pass = md5($pass);

$query_string = "SELECT username , password FROM accounts WHERE loginname = '$user' LIMIT 1";
$query = mysql_query($query_string)or die(mysql_error());
$numrows = mysql_numrows($query);

if ( $numrows == 0 ){
$errormsg = "There is no record of a user with that login-name.";
}else{

$db_info = mysql_fetch_row($query);

$username = $db_info[0];
$password = $db_info[1];

if ( strtolower($pass) != strtolower($password) ){
$errormsg = "The password you inputted is in-correct.";
}else{

$_SESSION["username"] = $username;

$ip = $_SERVER["REMOTE_ADDR"];
$now = time() + 300;
$update_string = "UPDATE accounts SET ip = '$ip' , activity = '$now' WHERE username = '$username' LIMIT 1";
mysql_query($update_string)or die(mysql_error());

Header("Location: ???.php");

}}}}}}}}

mysql_close();
?>

 

obviously output the error message like

 


if ( !(empty($errormsg) ){
echo $errormsg;
}

 

Or however you wish it to be displayed.

 

Hope it's use full to you....

Show Errors and it will tell you where the error is.

 

Also, when troubleshooting, remove the @ suppressors.

 

does this look right? For some reason the result is a blank white page. I am not sure where the error is occurring.

 

(lemme know if && is legal in sql queries, I don't think they are)

 

&& and || are both perfectly valid in mysql. Your code looks good, I would however follow revraz's advice and remove all instance of the error supressor, its hard to find errors when they are being hidden.

I took out the @ symbol, but I still get the blank white page. If I don't have access to change the PHP .ini file, how can I add error handling into the script itself? I cannot remember exactly how that is done.

 

here is my script as it is now.

 


<?php

if (isset($_POST['submit'])) {
//connect to MySQL and select database to use
$connection = mysql_connect("localhost","uname","PW") or die(mysql_error());
$db = mysql_select_db($db_name,$connection) or die(mysql_error());
$username = mysql_real_escape_string($_POST['loginemail']);
$userpw = mysql_real_escape_string($_POST['loginpw']);
$sql = "SELECT loginemail,loginpw FROM RegistrationForm WHERE loginemail = '$username' AND loginpw = '$userpw'";
if ($result = mysql_query($sql)) {
if (mysql_num_rows($result)) {
session_start();
$_SESSION['logged'] = true;
header("Location: console.php");
} else {
        header("Location: index.php?error=x");
      }
    }
  }


?>


your right I didn't! I took that line out because I don't think it was needed.

 

the error I get now is this:

 

 

Notice: Undefined index: loginemail in /var/www/vhosts/shadowmarket.com/httpdocs/real-estate/x/login.php on line 7

 

Notice: Undefined index: loginpw in /var/www/vhosts/shadowmarket.com/httpdocs/real-estate/x/login.php on line 8

 

those two lines are this:

 

$username = mysql_real_escape_string($_POST['loginemail']);
$userpw = mysql_real_escape_string($_POST['loginpw']);

 

can someone please elaborate on what the errors mean?

here it is. I think I see what you mean the input information has to match what is in login.php, so it would be input name="loginemail" and input name="loginpw"?

 


<?
include('x.php');
$error = $_REQUEST['error'];
?><br>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<?
include('header_admin.php')
?>
<body>
<div align="center">
  <table width="750" border="1" align="center" cellpadding="0" bordercolor="#000000" bgcolor="#FFFFFF">
    <tr>
      <td bordercolor="#FFFFFF"><div align="center">
        <table width="750" border="0" align="center" cellpadding="5" bordercolor="#FFFFFF" bgcolor="#FFFFFF">
          <tr>
            <td colspan="2"><div align="center"><img src="../template_images/x_top.gif" width="750" height="75"></div></td>
          </tr>
          <tr>
            <td colspan="2" valign="top"><? include('menu.php'); ?></td>
          </tr>
	  <?
 if($logout)
   {
   print"<tr bgcolor='#CCFF00'>";
   }
   elseif($error)
   {
   print"<tr bgcolor='#FF0000'>";
   }
else
   {
print"<tr>";
   }

   ?>
            <td colspan="2" valign="top"><div align="center">
              <table width="100%"  border="1" align="center" cellpadding="0" bordercolor="#999999" bgcolor="#FFFFFF">
                <tr>
                  <td valign="top" bordercolor="#FFFFFF" bgcolor="#eeeeee"><div align="center" class="style1">System Administration
                      <? include('xver.txt');?>
Console</div></td>
                </tr>
              </table>
              <form action="login.php" method="post" name="xconsole" id="xconsole">
              <table width="100%"  border="1" align="center" cellpadding="0" bordercolor="#999999" bgcolor="#FFFFFF">
                <tr>
                  <td width="25%" bordercolor="#FFFFFF"><div align="right" class="style4">                    	 <?
				if($logout == "x")
   {
   print"<b>Log Out X Console = Success !</b>";
   }
   if($error)
   {
   print"<b>X Console Login = Error !</b>";
   }
   					if($logout == "y")
   {
   print"<b>Log Out X Console = Success ! Login Updated</b>";
   }

   ?>
</div></td>
                  <td width="25%" bordercolor="#FFFFFF"><div align="right"><span class="style4">Email Address </span></div></td>
                  <td width="50%" bordercolor="#FFFFFF"><div align="left" class="style4">
                    <input name="q" type="text" id="q">
                  </div></td>
                </tr>
                <tr>
                  <td colspan="2" bordercolor="#FFFFFF"><div align="right" class="style4">Password</div></td>
                  <td valign="top" bordercolor="#FFFFFF"><div align="left" class="style4">
                    <input name="t" type="password" id="t">
                  </div></td>
                </tr>
              </table>
                  <br>
                  <input type="submit" name="Submit" value="X Console Login">
                  <br>
              </form> 
            </div></td>
          </tr>
          <tr>
            <td width="448"><div align="center" class="style9">
              <div align="left"><a href="http://www.listingagent.ca" target="_blank"> <? print"$fc"; ?> : Installed Version # <? include('ver.txt'); include('xver.txt');?></a></div>
            </div></td>
            <td width="290"><div align="center" class="style9">
              <div align="right"><a href="index.php"><? print"$x_console"; ?></a></div>
            </div></td>
          </tr>
        </table>
      </div></td>
    </tr>
  </table>
</div>
</body>
</html>

now I am getting the following errors.

 

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'apache'@'localhost' (using password: NO) in /var/www/vhosts/shadowmarket.com/httpdocs/real-estate/x/login.php on line 7

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /var/www/vhosts/shadowmarket.com/httpdocs/real-estate/x/login.php on line 7

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: Access denied for user 'apache'@'localhost' (using password: NO) in /var/www/vhosts/shadowmarket.com/httpdocs/real-estate/x/login.php on line 8

Warning: mysql_real_escape_string() [function.mysql-real-escape-string]: A link to the server could not be established in /var/www/vhosts/shadowmarket.com/httpdocs/real-estate/x/login.php on line 8

Warning: mysql_query() [function.mysql-query]: Access denied for user 'apache'@'localhost' (using password: NO) in /var/www/vhosts/shadowmarket.com/httpdocs/real-estate/x/login.php on line 10

Warning: mysql_query() [function.mysql-query]: A link to the server could not be established in /var/www/vhosts/shadowmarket.com/httpdocs/real-estate/x/login.php on line 10

 

is this due to a code problem or a database connection issue?

<?php

if (isset($_POST['submit'])) {
//connect to MySQL and select database to use
$connection = mysql_connect("localhost","uname","PW") or die(mysql_error());
$db = mysql_select_db($db_name,$connection) or die(mysql_error());
$username = mysql_real_escape_string($_POST['loginemail'], $connection);
$userpw = mysql_real_escape_string($_POST['loginpw'], $connection);
$sql = "SELECT loginemail,loginpw FROM RegistrationForm WHERE loginemail = '$username' AND loginpw = '$userpw'";
$result = mysql_query($sql, $connection);
if (mysql_num_rows($result) != 0) {
session_start();
$_SESSION['logged'] = true;
header("Location: console.php");
} else {
        header("Location: index.php?error=x");
      }
    
  }


?>

 

Does that work?

I don't get a DB error anymore, but when I enter into the form a username/password that is in the database table RegistrationForm, I end up on the error page and not the succussfull login page. Not sure why?

 


<?php
error_reporting(E_ALL); ini_set('display_errors','1');
if (isset($_POST['Submit'])) {
//connect to MySQL and select database to use
//set up database and table names
$db_name ="shadowdata";
$table_name ="RegistrationForm";


//connect to MySQL and select database to use
$connection = @mysql_connect("localhost","username","password") or die(mysql_error());

$db = @mysql_select_db($db_name,$connection) or die(mysql_error());

$username = mysql_real_escape_string($_POST['loginemail']);
$userpw = mysql_real_escape_string($_POST['loginpw']);
$sql = "SELECT loginemail,loginpw FROM RegistrationForm WHERE loginemail = '$username' AND loginpw = '$userpw'";
if ($result = mysql_query($sql)) {
if (mysql_num_rows($result)) {
session_start();
$_SESSION['logged'] = true;
header("Location: console.php");
} else {
        header("Location: index.php?error=x");
      }
    }
  }


?>

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.