Click here to Skip to main content
15,884,388 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
hi i wave written a small application which accepts username and password in a form and validates it for empty text fields. After validation it has to navigate to login authentication page with username and password values passed using POST method and it checks MySQL database for user name and password. But in my code it is navigating to next page but values are not passed coz of which database is returning 0 rows and it is showing as success full authentication even if username and password is wrong. I have attached my code please help me in identifying the bug.

PHP code to validate form:
PHP
<?php
		
		//$msg = $_POST['msg'];
		$usernameerr = $passerr = "";
		$username = $pass = "";
		//echo "<p>" . $msg . "</p>";
		if ($_SERVER["REQUEST_METHOD"] == "POST")
		{	
			 
			if (empty($_POST["username"]))
			{
				$usernameerr = "Username is missing";
				$valid = false;
			}
			else
			{
			$username = test_input($_POST["username"]);
			$valid = true;
			}
   
			if (empty($_POST["password"]))
			{
				$passerr = "Password is missing";
				$valid = false;
			}
			else
			{
				$pass = test_input($_POST["password"]);
				$valid = true;
			}
			if($valid)
			{

				header('Location: http://localhost/tabs/validate_login.php');
				exit();
			}
		}

		function test_input($data)
		{
			$data = trim($data);
			$data = stripslashes($data);
			$data = htmlspecialchars($data);
			return $data;
		}
?>


html form to accept username and password:

HTML
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" style= " margin-left:25%; " >
        <table  width= 100% height= 100%;>
            <tr>
                <td width = 60px><label for="username">Username</label></td>
                <td width = 60px><input type="text" 
                  name="username" id="username"></td>		
            </tr>
            <tr>
                <td width = 60px><label for="password">Password</label></td>
                <td width = 60px><input name="password" 
                  type="password" id="password"></input></td>
            </tr>
			<tr>
			</tr>
			<tr>
			</tr>
			<tr>
			</tr>
			<tr>
			</tr>
            <tr>
			</table>
			<table >
                <td width = 100px align="center"><input type="submit" value="Submit"/>
                <td width = 100px align = "center"><input type="reset" value="Reset"/>
            </tr>
        </table>
    </form>	


PHP code to authenticate user:

PHP
<?php

	// Grab User submitted information
	$username = $_POST["username"];
	$pass = $_POST["password"];

	
	
	// Connect to the database
	$con=mysqli_connect("localhost","root","Quest1234","maintenance_help");
	// Make sure we connected succesfully
	if(! $con)
	{
		die('Connection Failed'.mysql_error());
	}

	// Select the database to use
	$result = mysqli_query($con,"SELECT username, pass FROM login WHERE username = '$username'");
	$row = mysqli_fetch_array($result);
	$match  = mysql_num_rows($result);
	
	if($row["username"]==$username && $row["pass"]==$pass)
	{
	//echo $username;
	//echo $pass;
	//echo "<p>" . $row['username'] . "</p>";
	//echo "<p>" . $row['pass'] . "</p>";
		echo "success";
	//	echo "<p> apple " . $match . "</p>";
		//echo "<script> window.location.assign('stockform.php'); </script>";
	}
	else
	{
		//$msg = "Invalid Username or Password";
		//$_POST['msg'];
		//header('Location:  http://localhost/tabs/login.php');
		echo "invalid username or password";
	}
?>
Posted
Updated 19-Feb-14 19:57pm
v2
Comments
EZW 21-Feb-14 0:51am    
Why are you going between mysqli functions and mysql? For example, you have mysqli_fetch_array and mysql_num_rows... and another question... did you recently start learning PHP? You're doing below the minimum of the validation (you really need to do better... you have left it open to SQL injection attacks), but you aren't doing anything about the errors... I'm also a bit confused on why you have two PHP pages that processes one form...
Member 10349202 21-Feb-14 0:59am    
yes i am very new to PHP. I am learning PHP and MySQL online and doing some basic examples. ya i was confused between mysql and mysqli, ill correct it. And i did not get you regarding SQL injection attack. Thanks for your time in looking at my code.
EZW 21-Feb-14 1:19am    
Look into mysqli prepare and mysqli bind params. That would dramatically increase the security of your SQL. Or simply use mysqli_real_escape_string()...
Member 10349202 21-Feb-14 1:22am    
I really don't know what all these are. But i will learn and understand. thanks for your help.

1 solution

Problems to fix:

First Code Block:
You have to if()..else's, both of which set the value of $valid. If the first one fails (i.e., no username) but the second one passes, then your code will see $valid=true.

Use $validPwd and $validName -> test if Both are true.

Also, there's usually no reason to check if server method were get or post. If you retrieve the data using $_REQUEST[''], then it will always work.

At your top, use something like:

$username = (isset($_REQUEST['username']))?$_REQUEST['username']:'';
$password = (isset($_REQUEST['password']))?$_REQUEST['password']:'';

Then you can test $username and $password.

Finally, try a SQL query something like:

$tsql = "SELECT count(username) from YOURTABLE where username='$username' AND password='$password'";

No matches (count==0) means failure;
 
Share this answer
 
Comments
Member 10349202 21-Feb-14 1:03am    
Thanks for your answer. if() else condition for validation and sql query helped me solving this.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900