PHP password_verify() does not verify successfully - javascript

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.

Related

PHP Javascript Mysql Insert

I am trying to use java-script prompt to insert values into MySQL. I have a html file and a php file.
The html files saved as Test.html:
<button onclick="myFunction()">Create Project</button>
<script>
function myFunction() {
var project = prompt("Please enter project name");
if (project != null && project !="") {
$.post("conn.php", { project : project });
}
}
</script>
The conn.php:
<?php
$servername = "localhost";
$username = "root";
$password = "Password";
$dbname = "db1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$proj = $_POST['project'];
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>
The conn.php works perfectly and inserts values if I remove the post parameter.
For example, instead of this:
$proj = $_POST['project'];
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";
if i use:
$proj = "NewProject";
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";
NewProject gets inserted into the database.
I am not sure if I am missing something in my index.html which is not posting the value in the prompt to php script. I have tried echo $_POST['project']; instead of inserting into MySQL. The echo is missing.
I have run your given code, it runs only i have added the jquery link above script code
Please check this correction,
<button onclick="myFunction()">Create Project</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function myFunction() {
var project = prompt("Please enter project name");
if (project != null && project !="") {
$.post("conn.php", { project : project },function(response){
console.log(response);
});
}
}
</script>
and also i have added isset() function with $_POST param in conn.php file
<?php
$servername = "localhost";
$username = "root";
$password = "Password";
$dbname = "db1";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$proj = isset($_POST['project'])?$_POST['project']:'';
$sql = "INSERT INTO projects (project_name) VALUES ('$proj')";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
?>

Why is hashed password not matching from value in database?

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

Jquery ajax call not working if using connection in include file

I can't figure out why jquery ajax post call not working if I used connection on include php file though I'm getting right response from php. Kindly tell me what's the explanation behind this
This is on my DB file
<?php
$host = "mysql2.000webhost.com";
$username = "a212_mt5199";
$password = "secret";
$db = "a211_mydb";
$con = new mysqli ($host, $username, $password, $db);
GLOBAL $con;
if ($con->connect_error) {
die ("Error:" . $con->connect_error);
}
?>
This including the above is not working
<?php
include("db.php");
// set parameters and execute
$myusername=$_POST['name'];
$mypassword=$_POST['pwd'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$stmt = $con->prepare("SELECT username, password FROM members WHERE username=? and password=?");
$stmt->bind_param("ss", $myusername, $mypassword);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
// Mysql_num_row is counting table row
$count=$stmt->num_rows;
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");
echo 'true';
$_SESSION['user_name']= $username;
} else {
echo "Wrong Username or Password";
}
$stmt->close();
$con->close();
?>
This is working
<?php
$host = "mysql2.000webhost.com";
$username = "a212_mt5199";
$password = "secret";
$db = "a211_mydb";
$con = new mysqli ($host, $username, $password, $db);
if ($con->connect_error) {
die ("Error:" . $con->connect_error);
}
// set parameters and execute
$myusername=$_POST['name'];
$mypassword=$_POST['pwd'];
// To protect MySQL injection (more detail about MySQL injection)
$myusername = stripslashes($myusername);
$mypassword = stripslashes($mypassword);
$stmt = $con->prepare("SELECT username, password FROM members WHERE username=? and password=?");
$stmt->bind_param("ss", $myusername, $mypassword);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
// Mysql_num_row is counting table row
$count=$stmt->num_rows;
// If result matched $myusername and $mypassword, table row must be 1 row
if($count==1){
// Register $myusername, $mypassword and redirect to file "login_success.php"
session_register("myusername");
session_register("mypassword");
echo 'true';
$_SESSION['user_name']= $username;
} else {
echo "Wrong Username or Password";
}
$stmt->close();
$con->close();
?>
Able to solve issue by using DEFINE variable.

Save entire DOM in mysql

I am not sure if this is possible, but I am looking for a way to save the entire state of my webpage without explicitly saving each element to a database.
For example, I dynamically create buttons, checkboxes, text etc. until the webpage looks as it needs. Can I save the DOM as a string, or blob in a database, and parse it later the get the webpage back?
I have tried things like:
var doc = document.documentElement.outerHTML;
Then save the string to database but it doesn't work.
I am using an AJAX call to a PHP script to write to mysql:
jQuery.ajax({
type: "POST",
url: 'connect/database.php',
dataType: 'json',
data: {functionname: 'connect_to_database', arguments: [user_id, user, doc] },
success: function (obj, textstatus) {
if( !('error' in obj) ) {
}
else {
console.log(obj.error);
}
}
});
PHP looks like:
// connection script
$servername = "XXX";
$username = "XXX";
$password = "XXX";
$dbname = "XXX";
$user_id = $_POST['arguments'][0];
$user = $_POST['arguments'][1];
$string = $_POST['arguments'][2];
// create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "INSERT INTO table (user_id, user, string) VALUES ('$user_id', '$user', '$string')";
# $sql = "UPDATE crows_nest SET json_string='$configuration' WHERE user = '$user'";
if ($conn->query($sql) === TRUE) {
echo "New record created successfully";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
$conn->close();
Use a prepared statement to prevent problems with special characters in the document string.
$stmt = $conn->prepare("INSERT INTO table (user_id, user, string) VALUES (?, ?, ?)");
$stmt->bind_param("iss", $user_id, $user, $string);
if ($stmt->execute()) {
echo "New record created successfully.";
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}

instead using die in error

i'm currently making a registration page. It includes hashing of password and validation. When I use "die" it stops the form and displays the error. I want to display the error on the same page.
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
$ErrorTest ="";
if(!empty($_POST))
{
// Ensure that the user has entered a non-empty username
if(empty($_POST['username']))
{
$ErrorTest = "Please enter a username.";
}
if(empty($_POST['password']))
{
$ErrorTest = "Please enter a password.";
}
if(!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL))
{
$ErrorTest = "Invalid E-Mail Address";
}
$query = "
SELECT
1
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
$ErrorTest = "Failed to run query: " . $ex->getMessage();
}
$row = $stmt->fetch();
if($row)
{
$ErrorTest = "This email address is already registered";
}
$query = "
SELECT
1
FROM users
WHERE
email = :email
";
$query_params = array(
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
$ErrorTest ="Failed to run query: " . $ex->getMessage();
}
$row = $stmt->fetch();
if($row)
{
$ErrorTest = "This username is already in use";
}
$query = "
INSERT INTO users (
username,
password,
salt,
email
) VALUES (
:username,
:password,
:salt,
:email
)
";
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$password = hash('sha256', $_POST['password'] . $salt);
{
$password = hash('sha256', $password . $salt);
}
$query_params = array(
':username' => $_POST['username'],
':password' => $password,
':salt' => $salt,
':email' => $_POST['email']
);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
$ErrorTest = "Failed to run query: " . $ex->getMessage();
}
// This redirects the user back to the login page after they register
header("Location: myprofile.php");
$ErrorTest = "Redirecting to admin_login.php";
}
?>
the die ("please enter a username") I want to display it on the same page. I tried also to put it on a javascript but when I put wrong infomation on one textboxes, it pop-ups all the error and displays the query.
The way I'd go about it is replacing die with a variable assignment to $error
i.e.
die("Failed to run query: " . $ex->getMessage());
replace with
$error = ("Failed to run query: " . $ex->getMessage());
and then wrap your registration logic with conditional statements checking if is set or if empty (up to you)
On your form you can then output this message using echo.
Edit
As you're redirecting to another page and not processing on the same page then adjust your code to
if($ErrorTest != ''){
header("Location: register.php?error=".$ErrorTest);
}
else{
header("Location: myprofile.php");
}
On the register.php page just check for the $_GET['error'] and then output it.
You're also always registering the user even if it errors so may be worth adding this code into the 'else'

Categories