I am trying to code a simple validation exercise for a username, password combination that will validate input and point out to users where their errors are and I am getting a strange outcome that i cannot fathom out why.
If a user has a password called Password then the code validates, however if they have a password as Password1 then I get the response that the username and password combination is incorrect even though I have changed it in the database.
Would anyone have come across this issue before and how could I go about fixing it?
<html>
<head>
<title>Login</title>
<link rel="stylesheet" type="text/css" href="style.css"/>
</head>
<body>
<h1>Log In</h1>
<form action="login.php" method="post">
<ul id="login">
<li> Username: <br />
<input type ="text" name="username"/>
</li>
<li>
Password: <br/>
<input type="password" name="password"/>
</li>
<li>
<input type="submit" value="Log In"/>
</li>
<li>
Register
</li>
</ul>
<?php
$username = $_POST['username'];
$password = $_POST['password'];
function user_exists($username){
$server = 'localhost';
$user='root';
$password='';
$db = 'finance_checker';
$mysqli = mysqli_connect($server, $user, $password, $db);
if(mysqli_connect_errno($mysqli)){
echo "Failed to connect to MySQL".mysqli_connect_error();
}
$res = $mysqli->query("SELECT * FROM `users` WHERE `UserName` = '$username'");
return ($res->num_rows>0);
$res->close();
}
function userLogin ($username, $password){
$server = 'localhost';
$user='root';
$pass='';
$db = 'finance_checker';
$mysqli = mysqli_connect($server, $user, $pass, $db);
$res = $mysqli->query("SELECT * FROM `users` WHERE `UserName`='$username' AND `Password` = $password");
if($res&&$res->num_rows>0){
return true;;
}else{
return false;
}
}
if(empty($_POST)==false){
if(empty($username)==true ||empty($password)==true){
echo "Please complete both sections of the form!<br />";
} else if(empty($username)==true){
echo "You must enter a username!<br />";
} else if(empty ($password)==true){
echo "You must enter a password!<br />";
} else if (user_exists($username)==false){
echo "Username cannot be found. Click on the register link to create a new account.";
} else{
$login = userLogin($username, $password);
if($login == false){
echo 'Username and Password combination is not compatible!';
} else{
header("Location:home.php ");
}
}
}
?>
</body>
</html>
You're missing quotes:
...`='$username' AND `Password` = $password"
^-- ^--
Without them, you're inserting a bare word into the query, which MySQL will treat as a field name. Given taht 'password` works, remember that
Password = password
would be valid sql, "where this field is equal to itself".
You want:
... AND `Password` = '$password`
note the quotes.
You are are also WIDE open for SQL injection attacks, so stop working on this code until you've learned about the problem and how to avoid it. Your actual problem stems from this injection vulnerability.
Related
I created a simple login portal but there are some issues and I tried several solutions.
This is my login.php file.
<!DOCTYPE html>
<html>
<head>
<title>Login Page</title>
<link rel="short icon" href="sopraicon.ico">
<link rel="stylesheet" href="login.css">
<body>
<form method="POST" action="process.php" >
<img src="soprasteria.png" alt="sopra steria" width="20%" align="center">
<img src="share.png" alt="share" id="img1" align="right">
<img src="search.png" id="img1" align="right">
<input type="text" class="search" name="search" placeholder="Search.."><br>
<br> <div class="sidediv"></div>
<p class="data">Sign in to Sopra Steria</p><br>
<h3 class="h3">User Login</h3>
<br><img src="Login.jpg" alt="login iamge" height="150px" width="170px"
align="left" style="padding-left:160px"><br> <b>Username:</b>
<br> <input type="text" placeholder="User Name" name="username"
required id="text">
<br> <b>Password:</b><br> <input type="password"
placeholder="Enter Password" name="password" required id="text" min="8">
<br> <button type="submit" id="logbtn"
name="submit">Login</button><br>
<div class="bottomdiv"></div>
</form>
</body>
</head>
</html>
This is my process.php file
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripcslashes($username);
$password = stripcslashes($password);
$username = mysql_real_escape_string($username);
$password = mysql_real_escape_string($password);
mysql_connect("localhost","root","");
mysql_select_db("login");
$result = mysql_query("select * from users where username='$username'
and password='$password'") or die("failed to query
database".mysql_error());
$row = mysql_fetch_array(result);
if($row['username']==$username && $row['password']== $password){
echo"login success";
}
else{
echo"failed";
}
?>
but I get error on WAMP server as you see in the image.
Please help me.. Thank you.
You to have to check if there is any record with this details in your table instead of matching user input with fetch data.
you have to check
if(mysql_num_rows ==1)
{
return true; //or redirect user to home page
}
else
{
return false;
}
first you get a warning telling you to abandon the mysql* function in favor of the mysqli functions.
Then you get the error the connection to the database using the standard user and no password failed.
connect to the database before you use mysql_real_escape_string.
When no connection is made when using the escape function, php will try to connect using a default user, which most often fails.
--
apart from that: stripslashes is a function one should not need, as the magic-quotes it tries to eleminate was removed from php years ago.
Now, you messup a password when it would contain en \
And the password: it's not stored in plain text, is it?
i tested your code it will working fine, but the error you are facing because you are using PHP 5.4 the function mysql_escape_string() is deprecated . So you need to do some changes in mysql driver file.Go to system\database\drivers\mysql\mysql_driver.php and find the escape_str function and replace the functions code with this code:
public function escape_str($str, $like = FALSE)
{
if (is_array($str))
{
foreach ($str as $key => $val)
{
$str[$key] = $this->escape_str($val, $like);
}
return $str;
}
$str = is_resource($this->conn_id) ? mysql_real_escape_string($str, $this->conn_id) : addslashes($str);
// escape LIKE condition wildcards
if ($like === TRUE)
{
return str_replace(array($this->_like_escape_chr, '%', '_'),
array($this->_like_escape_chr.$this->_like_escape_chr, $this->_like_escape_chr.'%', $this->_like_escape_chr.'_'),
$str);
}
return $str;
}
try this
$password=$_POST['password'];
$username = stripcslashes($username);
$password = stripcslashes($password);
if(!empty($username)&&!empty($password))
{
$query="SELECT username,password FROM users WHERE username='$username'
AND password='$password' ";
if($query_run= mysqli_query($conn, $query)){
$query_num_rows= mysqli_num_rows($query_run);
if($query_num_rows==NULL){
echo "Invalid Username/password combination";
} elseif($query_num_rows==1){
while ($row=mysqli_fetch_assoc($query_run)) {
$username=$row['username'];
$password=$row['password'];
echo' you are logged in <br>';
echo 'Welcome'.$username;
}
}
}
}else{
echo 'Please fill all fields';
}
}
}
Alright so i have been looking around for a simple login system and i have looked at many videos and noticed they are all using MYSQL and according to my webhost i need to use MYSQLi so my code is posted below, can someone help me, everytime i press login it just refreshes the page and does nothing
<?php
$error=''; //Variable to Store error message;
if(isset($_POST['submit'])){
if(empty($_POST['user']) || empty($_POST['pass'])){
$error = "Username or Password is Invalid";
}
else
{
//Establishing Connection with server by passing server_name, user_id and pass as a patameter
$host = "198.91.81.8";
$user = "iishnoii_admin";
$pass = "password";
$db = "iishnoii_seclog";
$con = mysqli_connect($host, $user, $pass, $db);
//sql query to fetch information of registerd user and finds user match.
$query = mysqli_query($conn, "SELECT * FROM users WHERE password='$pass' AND username='$user'");
$rows = mysqli_num_rows($query);
if($rows == 1){
header("Location: welcome.php"); // Redirecting to other page
}
else
{
$error = "Username of Password is Invalid";
}
mysqli_close($conn); // Closing connection
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>IIShNoII</title>
</head>
<body>
<div id="login-form">
<form method="post" action="index.php">
Username: <input type="test" name="username" /> <br /> <br />
Password: <input type="password" name="password" /> <br /> <br />
<input type="submit" name="submit" value="Log In" />
</div>
</body>
</html>
In your form, the names of the fields are username and password, but when you try to retrieve them in PHP with $_POST, you call them userand pass.
I am trying to connect my login page to Mongodb but i am encountering some error.Since I am trying it for the first time I am not completely familiar to this.I would like to know where I have gone wrong
This is the html page
<html>
<head>
<title> Login</title>
</head>
<body>
<form action="login.php" method="POST">
User Name:
<input type="text" id="username" name="username" />
Password:
<input type="password" id="password" name="password" />
<input name="submit" id="submit" type="submit" value="Login" />
</form>
</body>
</html>
This is PHP code:
<html>
<?php
if(isset($_POST['submit'])
{
$username = ($_POST['username']);
$password = ($_POST['password']);
if(empty($username))
{
echo "Empty or invalid email address";
}
if(empty($password)){
echo "Enter your password";
}
$con = new MongoClient();
// Select Database
if($con)
{
$db = $con->tickets;
// Select Collection
$collection = $db->Admin;
$qry = array("username" => $username,"password" => md5($password));
$result = $collection->findOne($qry);
if($result){
echo "You are successully loggedIn";
}
else
{ echo "unsuccessful";
}
} else {
die("Mongo DB not connected");
}
}
?>
</html>
There is nothing specific that would make it end just before ticket. So I don't think there is an exact answer that can be given.
However in cases like this, try narrow it down to a smaller problem, for example, does this work:
<html>
<body>
<?php
echo "Hello";
?>
</body>
</html>
If no, then you probably don't have PHP installed correctly or possibly not configured correctly.
If yes, build it up a tad:
<html>
<body>
<?php
echo $_POST['submitForm'];
?>
</body>
</html>
Etc, etc
As a side note, I am not encouraging the mix of PHP/HTML nor the direct use of $_POST - I am just building on the original question
You may want to use empty function on the $result.
So your php code must be like this:
<?php
if(isset($_POST['username']) && isset($_POST['password'])){
$username = ($_POST['username']);
$password = ($_POST['password']);
$pass_hash = md5($password);
if(empty($username)){
die("Empty or invalid email address");
}
if(empty($password)){
die("Enter your password");
}
$con = new MongoClient();
// Select Database
if($con){
$db = $con->tickets;
// Select Collection
$collection = $db->admin; // you may use 'admin' instead of 'Admin'
$qry = array("username" => $username, "password" => $pass_hash);
$result = $collection->findOne($qry);
if(!empty($result)){
echo "You are successfully loggedIn";
}else{
echo "Wrong combination of username and password";
}
}else{
die("Mongo DB not connected!");
}
}
?>
Also check your collection name. Is that 'admin' or 'Admin'
Hope this will help.
I Used same code but the unsuccessful login error occurs for me and I fixed it.hope it will be helpful!
try this
$result = $collection->findOne(array('username' =>'$username,'password' =>md5($password)));
Instead of
$qry = array("username" => $username,"password" => md5($password));
$result = $collection->findOne($qry);
I am trying to create a login page using wamp server kindly help me with the following code
<?php
$host = "localhost";
$user = "root";
$pass = "";
$db ="test"; //database name
if(isset($_POST['username']))
{
$username = $_POST['username'];
$password = $_POST['password'];
$sql ="SELECT * FROM users WHERE username ='$username' AND password ='$password'";
$result = mysqli_query($sql);
if(mysqli_num_rows($result==1))
{
echo "logged in successfully"."<br/>";
}
else
{
echo "invalid password or username retry";
}
}
?>
<html>
<head>
<title>login</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<form name="login" method="post" action="login.php">
Username <input type="text" name="username">
<br/><br/>
Password <input type="password" name="password">
<br/><br/>
<input type="submit" value="login" name="submit">
</form>
</body>
</html>
I think you had read some wrong articles and messed up .The correct code should be like this
$host = "localhost";
$user = "root";
$pass = "";
$db ="test"; //database name
// This line connects to DB
$con = mysqli_connect($host, $user, $pass,$db) or die ("Please check your server connection.") ;
if(isset($_POST['username']))
{
// use mysqli_real_escape_string to prevent SQL Injection
$username = mysqli_real_escape_string($con,$_POST['username']);
$password = mysqli_real_escape_string($con,$_POST['password']);
//write a query to select
$sql ="SELECT * FROM users WHERE username ='".$username."' AND password ='".$password."'";
//execute the written query using mysqli_query()
$result = mysqli_query($con,$sql);
//----------------------^----------- This is the missed parameter
//check the no of rows returned
if(mysqli_num_rows($result) == 1) { echo "logged in successfully"; }
else { echo "invalid password or username retry"; }
}
The line
if(mysqli_num_rows($result==1)) // You are passing boolean parameter here.
is incorrect
It should be:
if(mysqli_num_rows($result)==1) // You are passing result set here, which is expected.
Alright, SO. After about five hours of sifting through potential duplicates and applying would-be solutions to my project and even downloading a PHP IDE to make sure that my syntax is all nice and tidy for everyone.. I am finally at the point where I need some advice.
My two problems (which may be related):
When someone logs in, successfully with the test parameters I have stored in the DB, they are not redirected (maybe my if statement is not correct?)
When the page loads without first attempt, my "wrong password - username combination" message is displaying. I'm fairly certain as to why but not too sure how to fix it.
<?php session_start(); // this line of code has been added by the instruction of a comment.
if(isset($submit)) {
$username = $_POST['username'];
$password = $_POST['password'];
}
$con = mysqli_connect("***","***","***","***");
$S_username = mysqli_real_escape_string($con, $username);
$S_password = mysqli_real_escape_string($con, $password);
if(mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$sql = mysqli_query($con, "SELECT * FROM `users` WHERE `username` = '$S_username' AND `password` = '$S_password'");
if(!$sql) {
die(mysqli_error($con)) ;
}
$check_again = mysqli_num_rows($sql);
if($check_again == 1) {
session_start(); // this line of code has been deleted
$_SESSION['logged in'] = TRUE;
$_SESSION['username'] = $S_username;
header("Location: http://terrythetutor.com/submitvideo.php");
}
else {
echo "Your username and password combination was not recognised. Please try again." ;
}
?>
<html>
<head>
<title>Login Page</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<?php include_once 'googleanalytics.php'; ?>
<body>
<a href="http://terrythetutor.com">
<div class="banner"> </div>
</a>
<?php include 'menu.php'; ?>
<h1 align="center">Please login to access restricted files</h1>
</br>
</br>
</br>
</br>
<div align="center">
<form action = "login.php" method = "post">
Username: <input type = "text" name = "username"></br></br>
Password: <input type = "password" name = "password"></br></br>
<input type = "submit" value = "Login" name="submit">
</form>
</div>
</body>
</html>
Any and all feedback is welcomed. Thank you.
use session_start(); only once and at the top ..