I cannot verify a password using password_verify. I used BCRYPT for password hashing. Help me find mistake in this code and how do I bind variables in the below select statement:
<?php
if (isset($_POST['submit'])) {
// echo "ok";
$con = connect();
$email = $_POST['email_id'];
$pass_word = $_POST['pass_word'];
if ($con) {
$query = mysqli_query($con,"select * from login where email_id='".$email."'");
$rows = mysqli_num_rows($query);
if ($query) {
$row = mysqli_fetch_assoc($query);
if ($row) {
$hash = $row['password'];
if (password_verify($pass_word,$hash) {
echo '<strong>Successful' ;
} else {
echo "Invalid Password";
}
}
}
} else {
die("Connection Error");
}
}
?>
missing parenthesis:
change here
if(password_verify($pass_word,$hash)
to
if(password_verify($pass_word,$hash))
Extended as request:
"select * from login where email_id='".$email."'";
becomes
"select * from login where email_id= ?";
which is passed to the $mysqli::prepare:
$stmt = $con->prepare("SELECT * FROM login WHERE email_id= ?");
$stmt->bind_param( "s", $email); // "ss' is a format string, each "s" means string
$stmt->execute();
$stmt->bind_result($email);// then fetch and close the statement
need a closed parenthes here in
if(password_verify($pass_word,$hash)
also your query is exposed to sql injection try to prepare it and bind the parameter with
$query=$conn->prepare($con,"select * from login where email_id=?");
$query->bind_param('s',$email); //change 's' with 'i' if you are expecting an integer
$query->execute()//to execute the query
Use this for bind param
$stmt = $con->prepare("select * from login where email_id=?");
$stmt->bind_param("s", $email);
$stmt->execute();
Related
I'm trying to do an execution of a query and see if it goes well, but right now it doesn't enter the IF or ELSE.
I had it on mysqli procedural and all worked flawlessy now I'm trying to change it to object oriented and it won't enter inside if/else.
if(isset($_POST['submit']))
{
$email = $_POST["email"];
$password = md5($_POST["password"]);
$query = "SELECT * FROM Users WHERE Email=? AND Password=?";
$stmt = $conn->prepare($query);
$stmt->bind_param('ss', $email,$password);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows == 1)
{
?>
<script type="text/javascript">
alert("INSIDE");
</script>
<?php
$row = $result->fetch_assoc();
if(isset($_POST['remember']))
{
$_SESSION["remember"] = "1";
}
$_SESSION["username"] = $row['Username'];
$_SESSION['check'] = "1";
$_SESSION['ID'] = $id;
$_SESSION['permission'] = $row['Admin'];
header("Location: dashboard.php");
exit;
}
else
{
?>
<script type="text/javascript">
alert("Credentials Are Wrong!");
</script>
<?php
exit;
}
$stmt->close();
}
Thank you all.
You should be using
$stmt->bind_result($col1, $col2 ...);
and
$result = $stmt->fetch();
in order to access the data from the query, rather than
$conn->query($stmt);
(an example is provided at https://secure.php.net/manual/en/mysqli-stmt.fetch.php). Note that for this to work you will need to specify the column names you want to fetch from the database, rather than using * in your SQL query, and for each column data is fetched from in the query, you should have a variable for in the fetch() parameters, so for example, something as follows should work (note these may not match the names of your database columns):
$email = $_POST["email"];
$password = md5($_POST["password"]);
$stmt = $conn->prepare("SELECT ID, Name FROM Users WHERE Email=? AND Password=?");
$stmt->bind_param('ss', $email, $password);
$stmt->execute();
$stmt->bind_result($id, $name);
$stmt->fetch();
$stmt->close();
echo $id . ': ' . $name;
Updated Answer
You are very close. Use $result = $stmt->get_result(); instead of $result = $stmt->query; to check to see if the query returned a result or not.
$email = $_POST["email"];
$password = md5($_POST["password"]);
$query = "SELECT * FROM Users WHERE Email = ? AND Password = ?";
$stmt = $conn->prepare($query);
$stmt->bind_param('ss', $email, $password);
$stmt->execute();
$result = $stmt->get_result();
if($result->num_rows !== 0){
if(isset($_POST['remember'])){
$_SESSION["remember"] = "1";
}
$_SESSION['check'] = "1";
$_SESSION['ID'] = $row['ID'];
header("Location: dashboard.php");
exit();
}else{
echo
'<script type="text/javascript">
alert("Credentials Are Wrong!");
</script>';
exit();
}
$stmt->close();
As several have already stated in their comments do not use MD5 for password hashes. PHP has it's own built in functions for handling passwords. Please research Password_has() and Password_verify(). Spend the time to research and implement these now instead of later. It will save you time.
I want to find out how to output data from database based on a single key,for example my database column are :
kodeDosen(PrimaryKey),namaDosen,email,telepon,password
and my login screen the user can only input kodeDosen and password,and i want to show the other data exept password,this is my register php:
<?php
include 'connectdb.php';
$data = json_decode(file_get_contents('php://input'), true);
$kodeDosen =$data["kodeDosen"];
$namaDosen = $data["namaDosen"];
$email = $data["email"];
$telepon = $data["telepon"];
$password= $data["password"];
$message = array("message"=>"Success");
$failure = array("message"=>"Failure,kodeDosen already used");
$sql = "INSERT INTO tbl_dosen (kodeDosen, namaDosen, email, telepon, password) VALUES ('$kodeDosen', '$namaDosen', '$email', '$telepon','$password')";
if (mysqli_query($conn, $sql)) {
echo json_encode($message);
} else {
echo json_encode($failure) ;
}
?>
and this is my login php:
<?php
include 'connectdb.php';
$data = json_decode(file_get_contents('php://input'), true);
$kodeDosen =$data["kodeDosen"];
$password = $data["password"];
$message = array("message"=>"Data found");
$failure = array("mesage"=>"Data not found");
if ($stmt = mysqli_prepare($conn, "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen =? and password = ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ss", $kodeDosen,$password);
/* execute query */
mysqli_stmt_execute($stmt);
/* store result */
mysqli_stmt_store_result($stmt);
if(mysqli_stmt_num_rows($stmt) > 0) {
echo json_encode($row);
}else {
echo json_encode($failure);
}
}
?>
It's not a good idea to insert a variable directly into an SQL query because of SQL injection.
I would suggest to use prepared statements on both of the queries. To pull the result from the db with prepared statements it's something like:
OOP style:
$stmt = $db->prepare("SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen = ? and password = ?");
$stmt->bind_param('ss', $kodeDosen, $password);
$stmt->execute();
$result = $stmt->get_result();
while ($row = $result->fetch_assoc()) {
//result is in row
var_dump($row);
}
Procedural style:
$stmt = mysqli_prepare($conn, "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen = ? and password = ?");
mysqli_stmt_bind_param($stmt, 'ss', $kodeDosen, $password);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = $result->fetch_assoc()) {
//result is in row
var_dump($row);
}
You can change in sql SELECT statement in login.php
$sql = "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen ='$kodeDosen' and password = '$password'";
in SELECT * means return all columns.
I think you want echo json_encode($row); rather than echo json_encode($message);
Try:
<?php
include 'connectdb.php';
$data = json_decode(file_get_contents('php://input'), true);
$kodeDosen =$data["kodeDosen"];
$password = $data["password"];
$message = array("message"=>"Data found");
$failure = array("mesage"=>"Data not found");
if ($stmt = mysqli_prepare($conn, "SELECT kodeDosen, namaDosen, email, telepon FROM tbl_dosen WHERE kodeDosen =? and password = ?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "ss", $kodeDosen,$password);
/* execute query */
mysqli_stmt_execute($stmt);
/* store result */
$result = mysqli_stmt_get_result($stmt);
$row = mysqli_fetch_assoc( $result );
if(mysqli_num_rows($result) > 0) {
echo json_encode($row);
}else {
echo json_encode($failure);
}
}
?>
This is where i get the issue
$username = $_POST['username'];
$password = $_POST['password'];
$username = mysqli_real_escape_string ($con, $username);
$password = mysqli_real_escape_string ($con, $password);
/* create a prepared statement */
if ($stmt = mysqli_prepare($con, "SELECT password, admin, id FROM members WHERE username=?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $username);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $hash, $admin, $id);
mysqli_stmt_store_result($stmt);
if($stmt->num_rows == 1) { //To check if the row exists
if($stmt->fetch()) {
if (password_verify($password, $hash)) {
$sql4 = "UPDATE members SET last_login='".$today."' WHERE id='".$id."'";
if ($con->query($sql4) === TRUE) {
$_SESSION['username'] = $username;
$_SESSION['admin'] = $admin;
header("location:staff_portal/");
} else {
echo "Contact Admin as Record can't be updated.";
}
{
echo "Invalid password.";
}
}
} else {
echo "Username or Password is wrong.";
}
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($con);
?>
The "Username or Password is wrong." is working just nothing else
You are missing an ELSE in your code. Nicely indented code shows this in a second
See the code I have annotated where.
You are also using mysqli_real_escape_string once where it is not needed and once where it can actually cause you problems
$username = $_POST['username'];
$password = $_POST['password'];
// not needed
//$username = mysqli_real_escape_string ($con, $username);
// dangerous, as it may change the passwrd entered by the user
// and as its not used in a concatenated query unnecessary anyway
//$password = mysqli_real_escape_string ($con, $password);
/* create a prepared statement */
if ($stmt = mysqli_prepare($con, "SELECT password, admin, id FROM members WHERE username=?")) {
/* bind parameters for markers */
mysqli_stmt_bind_param($stmt, "s", $username);
/* execute query */
mysqli_stmt_execute($stmt);
/* bind result variables */
mysqli_stmt_bind_result($stmt, $hash, $admin, $id);
mysqli_stmt_store_result($stmt);
if($stmt->num_rows == 1) { //To check if the row exists
if($stmt->fetch()) {
if (password_verify($password, $hash)) {
//I dont see anywhere where $today is initialized
// NOW() would have been all you needed assuming last_login
// Is a DATETIME/DATE/TIMESTAMP Column
$sql4 = "UPDATE members SET last_login='".$today."' WHERE id='".$id."'";
if ($con->query($sql4) === TRUE) {
$_SESSION['username'] = $username;
$_SESSION['admin'] = $admin;
header("location:staff_portal/");
} else {
echo "Contact Admin as Record can't be updated.";
}
} else {
//----------^^^^^^ this was missing
echo "Invalid password.";
}
}
} else {
echo "Username or Password is wrong.";
}
/* close statement */
mysqli_stmt_close($stmt);
}
/* close connection */
mysqli_close($con);
?>
Can someone please take a look at this block of code? I am very new to the PDO method, for some reason this keeps causing a 500 error whenever I submit.
I have narrowed it down to this:
Could it be this part? $hash = $stmt['hash'];
if(empty($response['error'])){
$stmt = $db->prepare("SELECT * FROM Login WHERE username= :username"); // Prepare the query
// Bind the parameters to the query
$stmt->bindParam(':username', $username);
//Carry out the query
$stmt->execute();
$hash = $stmt['hash'];
$affectedRows = $stmt->rowCount(); // Getting affected rows count
if($affectedRows != 1){
$response['error'][] = "No User is related to the Username";
}
if(password_verify($password, $hash))
{
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $stmt['ID'];
}
else
{
$response['error'][] = "Your password is invalid.";
}
}
If you need more info please ask I will be happy to supply anything I can.
You need to fetch the result of the query to have it accessible. I'm not sure this is your issue, I'd think $hash would just be set to Resource Id#x, not what you want but not a 500. Here's how to fetch (http://php.net/manual/en/pdostatement.fetch.php) though
$stmt = $db->prepare("SELECT * FROM Login WHERE username= :username"); // Prepare the query
// Bind the parameters to the query
$stmt->bindParam(':username', $username);
//Carry out the query
$stmt->execute();
//if you will only be getting back one result you dont need the while or hashes as an array
while($result = $stmt->fetch(PDO::FETCH_ASSOC)){
$hashes[] = $result['hash'];
}
Here's a thread on enabling error reporting PHP production server - turn on error messages
Also you don't have to bind to pass values with the PDO. You also could do
$stmt = $db->prepare("SELECT * FROM Login WHERE username= ?"); // Prepare the query
$stmt->execute(array($username));
Your code is really messy. Just to help you with start point:
if (empty($response['error'])) {
if (isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $db->prepare("SELECT * FROM Login WHERE username= :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$hash = $row['hash'];
if(password_verify($password, $hash)) {
$_SESSION['username'] = $username;
$_SESSION['userid'] = $stmt['ID'];
} else {
$response['error'][] = "Your password is invalid.";
}
} else {
$response['error'][] = "No User is related to the Username";
}
} else {
$response['error'][] = "Username is not set!";
}
}
$valid = mysqli_query($com,"select username,email from company_profile where username = ".$uname." or email = ".$email." ");
if ($valid=="")
{echo "email n username exists";}
else
{
echo "reg success";
}
Here is my code, it doesn't work is i was also sure. want to return result weather email or username exists in db or not.
what's the way to do it.
The mysqli_query method returns a resultset, not a scalar.
$result = mysqli_query($com, "SELECT ...", MYSQLI_STORE_RESULT);
if ( $result->num_rows() > 0 ) {
echo "query returned at least one row";
}
The code looks vulnerable to SQL injection, we don't see any references to the mysqli_real_escape_string function.
We'd prefer to see a prepared statement with bind variables, e.g.
if ($stmt = mysqli_prepare($com, "SELECT username,email from company_profile"
. " where username = ? OR email = ? "))
{
mysqli_stmt_bind_param($stmt, "ss", $uname, $email);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
while ($row = mysqli_fetch_array($result))
{
}
mysqli_stmt_close($stmt);
}