Why is hashed password not matching from value in database? - javascript

I have a registration form whose snippet is as follows-
$email=$_GET['email'];
$pass=$_GET['pass'];
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$password = hash('sha256', $pass.$salt);
for($round = 0; $round < 65536; $round++)
{
$password = hash('sha256', $password.$salt);
}
mysql_query("INSERT INTO user_tbl(email, password, salt) VALUES ('$email','$password','$salt')");
For a specific password following string is getting stored in db-
df22e53c7fb2d599d64597a04fd28ca47bc79675ac50a2381c9a17fd4e07b263
Now i also have a login form. Whose code snippet is as follows-
$email=$_GET['email'];
$pass=$_GET['password'];
$result=mysql_query("SELECT * from user_tbl where email='$email'");
$row=mysql_fetch_array($result);
$salt = $row['salt'];
$password = hash('sha256', $pass.$salt);
for($round = 0; $round < 65536; $round++)
{
$password = hash('sha256', $password.$salt);
}
if(strcmp($row['password'],$password)!=0)
{
echo "wrongpassword";
exit();
}
else
{
echo "Success";
}
Now i could see that the hashed password which the login form is evaluating to is also df22e53c7fb2d599d64597a04fd28ca47bc79675ac50a2381c9a17fd4e07b263 . Which is same as what registration form is submitting to database.
They should match. But they are not. The String compare test is always failing.
The length of both fields i.e. password and salt are 200 each and are of type VARCHAR which is sufficient i think because above algo will generate a 64 character long string only. Still What is the problem? Please help me out here.

You just need a simple correction in your IF condition:
if(strcmp($row['password'],$password)!==0) // change here :)
{
echo "wrongpassword";
exit();
}
else
{
echo "Success";
}
Please see the documentation: http://php.net/manual/en/function.strcmp.php

Related

Ajax success object

I'm trying to validate the form using AJAX. This is what I've done so far:
$('#login-form').submit(function(e) {
e.preventDefault();
var user = username.value;
var pass = password.value;
if (user != '' && pass != '') {
$('#login').html('Proccessing...');
$.ajax({
url: 'login.php',
type: 'POST',
data: {
username: user,
password: pass
},
processData: false,
contentType: false,
success: function(response) {
if (response == 'success') {
window.location.href = 'admin.php';
} else {
$('.login_message').html('Incorrect Credentails');
$('#login').html('Login');
}
}
});
} else {
$('.login_message').html('Fill All Fields');
$('#login').html('Login');
}
})
and it seems like response doesn't return success. Below is the login.php file
<?php
session_start();
$password = $username = '';
$_SESSION['user'] = $_SESSION['error'] = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
if (isset($_POST['login'])) {
include_once('db.php');
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$password = md5($password);
echo 'username: ' . $username . ' and ' . ' password: ' . $password;
$sql = "select * from users where username = '" . $username . "' limit 1";
$query = mysql_query($sql);
if ($query) {
$row = mysql_fetch_assoc($query);
$dbpass = $row['password'];
if ($password == $dbpass) {
;
$_SESSION['user'] = $username;
header('Location: admin.php');
} else {
$_SESSION['error'] = 'Wrong username or password!';
}
} else {
echo mysql_error();
}
}
}
?>
If it happens you have found the solution, please explain to me how you find the solution and what I've done wrong.
Thank you in advance.
Since this is ajax request,we need to send some response from server. As you did in your question check if(response=='success'). To do that, you need to send success to your client. If everything is ok (data send to server and query) then in your login.php edit this line
if($password == $dbpass) {
$_SESSION['user'] = $username;
//comment this line
//header('Location: admin.php');
echo "success";
} else {
$_SESSION['error'] = 'Wrong username or password!';
}
Here I put one line code echo "success"; and I believe this will resolve your issue.
Returning values from PHP back to JS
When using AJAX, I believe if you do echo in the PHP target file (here login.php) it will act as a return. Therefore the code after a echo will not run as you might expect.
Also in your code you have: echo $_SESSION['error'] = '';
Use == to compare two object, = is the assignment operator.
Retrieving AJAX data in PHP file
The use of the ajax() method from jQuery in your code looks correct to me. So when the call is made the information is sent asynchronously to the server. More precisely it will send the parameters to the PHP file you've specified in the ajax object properties: login.php.
In login.php you can access your passed parameters in the $_POST array.
You would have the following:
$username = $_POST['username'];
$password = $_POST['password'];
// process information...
$state = 'success'
// now you can return a JSON object back to your page
// I strongly recommend using a PHP array and converting it to JSON
// this way it's very easy to access it back with JS
$response = array(state=$state)
echo json_encode($response);
And back in your jQuery code you access the state value with response.state
if(response.state == 'success') {
alert('It is a succcess!');
}
Debugging PHP target files
Now you generally have problems in the code in this PHP files. And it's not an easy thing to debug it. So the way I proceed is: I set the parameters in stone in login.php for instance:
$username = 'usernameTest'; // $username = $_POST['username'];
$password = 'passwordTest'; // $password = $_POST['password'];
Then I would open the PHP file in a browser and run it do see if it echoes the object and if there are any bugs.
Then you can put back $username = $_POST['username']; and $password = $_POST['password'];.
Actual code
<?php
session_start();
if (isset($_POST['username'], $_POST['password']) {
include_once('db.php');
$username = strip_tags($_POST['username']);
$password = strip_tags($_POST['password']);
$password = md5($password);
$sql = "select * from users where username = '" . $username . "' limit 1";
$query = mysql_query($sql);
if ($query) {
$row = mysql_fetch_assoc($query);
$dbpass = $row['password'];
if ($password == $dbpass) {
$state = 'success';
} else {
$state = 'failed';
}
} else {
echo mysql_error();
}
}
Warning mysql(), md5() and SQL injections
Don't use the deprecated and insecure mysql_* functions. They have been deprecated since PHP 5.5 (in 2013) and were completely removed in PHP 7 (in 2015). Use MySQLi or PDO instead.
You are wide open to SQL Injections and should really use Prepared Statements instead of concatenating your queries. Using strip_tags() is far from a safe way to escape data.
Don't use md5() for password hashing. It's very insecure. Use PHP's password_hash() and password_verify() instead. If you're running a PHP version lower than 5.5 (which I really hope you aren't), you can use the password_compat library to get the same functionality.
- Magnus Eriksson

PHP header location function not working in form

I'm trying to make a registration form for my website. I'm using the code below. All the error handlers work fine since it's adding the users into my database. I've trid to add ob_start. I removed all white spaces using a plugin for sublime text. I tried to use javascript instead of php (top.window). I also tried to use full url instead of just directories. But when I click submit it doesnt redirect me to the address I put after Location. When I click the button it takes me to this php file but doesnt redirect me back to the registration page which is a seperate file(I know there are a lot of similar questions that have been asked but they dont seem to work for my situation).
Does anyone know how to fix that?
if (isset($_POST['submit'])){
include_once 'db.php';
$uid = mysqli_real_escape_string($conn, $_POST['uid']);
$pwd = mysqli_real_escape_string($conn, $_POST['pwd']);
$email = mysqli_real_escape_string($conn, $_POST['email']);
//error handlers
//Check for empty fields
if (empty($uid) || empty($pwd) || empty($email)) {
header("Location : /login/register.php?signup=empty");
exit();
} else{
//Check if input characters are valid
if (!preg_match("/^[a-zA-Z]*$/", $uid)) {
header('Location: /login/register.php?signup=invalid');
exit();
} else {
//Check if email is valid
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
header('Location : /login/register.php?signup=email');
exit();
} else {
$sql = "SELECT * FROM users WHERE user_uid='$uid'";
$result = mysqli_query($conn, $sql);
$resultCheck = mysqli_num_rows($result);
if ($resultCheck > 0) {
header('Location : /login/register.php?signup=usertaken');
exit();
} else {
//Hashing the password
$hashedPwd = password_hash($pwd, PASSWORD_DEFAULT);
//Insert the user into the databse
$sql = "INSERT INTO users (user_uid, user_pwd, user_email) VALUES ('$uid', '$hashedPwd', '$email');";
mysqli_query($conn, $sql);
header('Location : /login/register.php?signup=success');
exit();
}
}
}
}
} else {
header('Location : /login/register.php');
exit();
}
Solved - Removing space after "location" answer by Nigel Ren
Make sure you don't have a space after location and before the :...
header('Location : /login/register.php');
should be
header('Location: /login/register.php');
Try to use absolute URI
$host = $_SERVER['HTTP_HOST'];
header("Location: ".$host."/login/register.php?signup=empty");
replace all header to location.assign
header('Location : /login/register.php');
replace to
echo "<script>location.assign('/login/register.php')</script>";
after use location assign , maybe problem sol..

add more information to database without making a new database

I would like to know how users can add multiple images and new data. For example on the site that I'm doing, you can make a design and when you finish you upload it to the database along with your email address title of the design, keywords ect.
I would like to know how its possible to let the user create more designs and named them all in the same database just retrieve them with an email address. I would like to make a limit of 14 designs per email address. But with the database and code that I have now, it only lets one design it just updates every time a new design is created.
Can someone show me the way on how to do this? If you need more information please ask, thank you.
Here is my code:
$query='UPDATE shirt_table SET images="'.$_FILES['file4']['name'].'", images1="'.$_FILES['file1']['name'].'", images2="'.$_FILES['file2']['name'].'", images3="'.$_FILES['file3']['name'].'"
WHERE email= "'.$_SESSION['email'].'"';
if ($mysqli->query($query) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$mysqli->close();
I can see that the uploaded files have different names, you'll have to list the expected file names internally as an array and loop through it that way.
Another thing you need to take care of is when the user has like 13 designs uploaded already and wants to add 4 more designs. You need to decide if you will reject all or add only one. Here is an example I believe you can modify to your taste.
/*
CREATE TABLE `shirt_table` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`email_address` varchar(50) DEFAULT NULL,
`image_path` varchar(100) DEFAULT NULL,
`date_created` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
)
*/
<?php
include("lib/dbcnx.inc.php");
$mysqli = new mysqli(DB_SERVER, DB_USER, DB_PASSWORD, DB_NAME);
$begin = 1;
$end = 5;
$max_uploads = 14;
$sel_query = "select count(*) from shirt_table where email = '".$_SESSION['email']."'";
$result = $mysqli->query($sel_query);
echo $sel_query."<br/>";
$numrows = $result->num_rows;
$counter = 0;
if ($numrows > 0) {
$row = $result->fetch_row();
$counter = $row[0];
}
if ($counter < $max_uploads) {
$saved_dir = "designs/";
$design_files = array($_FILES['file4']['name'], $_FILES['file3']['name'], $_FILES['file2']['name'], $_FILES['file1']['name']);
$query = "INSERT INTO shirt_table (email, image_path, date_created) values ";
for ($i=$begin; $i<=$end; $i++) {
$query = $query ."('".$email."', '".$saved_dir.$design_files[$i-$begin]."', now())";
if ($i < $end)
$query = $query.", ";
}
echo $query."<br/>";
if ($mysqli->query($query) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;
}
$mysqli->close();
} else {
echo "You have exceeded ...";
$mysqli->close();
}
?>

Website Validation with php not working?

I am having trouble trying too check theses two inputs uname and passwod. I can get one to work on its own but I keep getting an error when I try to pass them both back up.
<?php
// define variables and set to empty values
$usernameErr="";
$passwordErr="";
$username= "";
$password="";
if ($_SERVER["REQUEST_METHOD"] == "POST")
{
if (empty($_POST["uname"]))
{
$usernameErr = " username is required <br>";
print $usernameErr;
}
else
{
$username = checkUserData($username);
}
if (empty($_POST["passwd"]))
{
$passwordErr = " password is required <br>";
print $passwordErr;
}
else
{
$password = checkUserData($password);
}
}
Here is were the problem is. I am passing down to check the data to stop attacks. I have tried multiple ways of joining them together but everything has failed.
function checkUserData($username)
{
$username = htmlspecialchars($username);
$username = trim($username);
$username = stripslashes($username);
return $username;
}
function checkUserData($password)
{
$password = htmlspecialchars($password);
$password = trim($password);
$password = stripslashes($password);
return $password;
}
I'm printing just to check it's working.
print ("welcome " .checkUserData($_POST["uname"]));
print ("welcome " .checkUserData($_POST["passwd"]));
?>
Any help would be great.
Both functions are doing the same thing so generalise them
function SanitizeData($var)
{
$var= htmlspecialchars($var);
$var= trim($var);
$var= stripslashes($var);
return $var;
}
Now in your checking process call
$username = SanitizeData($_POST["uname"]);
Or
$password = SanitizeData($_POST["passwd"]);
Although this sanitization is unnecessary at best and destructive at worst if you are going to use these fields in a query, it would be better to use a parameterized query and the PDO database extension.

PHP password_verify() does not verify successfully

I have checked all the similar questions and answers but none is working for me.
I am using the standard php hashing and verification method Below are my codes.
this the code for hashing the password
$passwordhash = password_hash($pwd, PASSWORD_DEFAULT);
the hashed output is then stored into a mysql database table the column is varchar datatype with size 255.
When the hash is retrieved and verified with a user presented password the verification returns a false.
the code for the verification is presented below.
if($rows2['user_name'] == $username) && password_verify($password ,$rows2['password'])){
$_SESSION['login_user']=$username; // Initializing Session
} else {
$error = "Username or Password is invalid";
}
however a verification of the hash with a correct password before storage provides a true answer.
here is the code for the verification before storage
if(password_verify($pwd ,$hashpassword )){
echo "<BR>"." the internal verify before storage"."<BR>";
}
this is the code for the storage of the hashed password.
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "datacentre";
// Create connection
$con = new mysqli($servername, $username, $password, $dbname , 3306);
if ($con->connect_error) {
die("Connection failed: " . $con->connect_error);
}
//mysql_select_db("$database", $con);
$sql= "INSERT INTO admin (user_name , password , time_created)
VALUES ('$u_name' , '$hash' , NOW() )";
if ($con->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $con->error;
}
$con->close();
This is the code for retrieving the hashed password.
if (isset($_POST['submit'])) {
if (empty($_POST['username']) || empty($_POST['password'])) {
$error = "Username or Password is invalid";
}
else
{
// Define $username and $password
$username=$_POST['username'];
$password=$_POST['password'];
// Create connection
$con = mysqli_connect($db_hostname, $db_username, $db_password, $db_database , 3306);
// Check connection
if(mysqli_connect_error()){
die("Connection failed: ".$con->connect_error);
}
// To protect MySQL injection for Security purpose
$username = stripslashes($username);
$password = stripslashes($password);
// Retrieve data from database
$sql="select * from admin where user_name ='$username'";
$result = mysqli_query($con,$sql);
while($rows2 = $result->fetch_assoc()){
if($rows2['user_name'] == $username) && password_verify($password ,$rows2['password'])){
$_SESSION['login_user']=$username; // Initializing Session
} else {
$error = "Username or Password is invalid";
}
}
$con->close(); // Closing Connection
}
}
}
looks like the problem is with how the database stores the hashed password.
Please will need a solution.

Categories