I am making a change password function. Currently It is just changing the password. But I want to amend it a bit. If email and password is valid then it should change the password, otherwise not. This is my code. Can anyone help me?
function CHANGE_PASSWORD($conn, $MSG)
{
$sql = $conn->prepare("UPDATE users SET password = ? WHERE email = ? AND password=?");
$sql->bind_param("sss", $newpass, $email, $password);
$email = $_REQUEST["EMAIL"];
$pass = $_REQUEST["PASSWORD"];
$newpass = $_REQUEST["NEW_PASSWORD"];
if ($sql->execute()) {
if($sql->affected_rows == 0) {
$json["STATUS"] = "FAIL";
$json["MESSAGE"] = "Invalid email / password";
} else {
$json["STATUS"] = "SUCCESS";
$json["MESSAGE"] = "Password Update Successful";
}
} else {
$json["STATUS"] = "ERROR";
$json["MESSAGE"] = "Please try again later.";
$json["ERROR"] = $sql->error_list;
}
$sql->close();
return json_encode($json);
#function ends
}
My Current URL looks like this
http://localhost/safespaces/server.php?REQUEST=CHANGE_PASSWORD&EMAIL=mr.aleem001%40gmail.com&PASSWORD=haioye&NEW_PASSWORD=12345
To fetch a row, use
$result = $sql->get_result();
$row = $result->fetch_assoc();
I Hope it Helps
Related
Please, help me look at this code for login, I want to verify if input password matches stored harsh password. This does not work. If i comment out If (password_verify..., i will be able to login otherwise, it wont login. i dont know where i got the code wrong and it doesnt want to verify password before login
if (isset($_POST['agentlogin-btn'])) {
$username= $_POST['username'];
$password = $_POST['password'];
function Is_email($user)
{
//If the username input string is an e-mail, return true
if (filter_var($user, FILTER_VALIDATE_EMAIL)) {
return true;
} else {
return false;
}
}
//validation
if (strlen($_POST['username']) < 1) {
$_SESSION['error'] = 'email or phone number required';
header("Location:register.php");
return;
}
if (strlen($_POST['password']) < 1) {
$_SESSION['error'] = 'password required';
header("Location:register.php");
return;
}
if (!isset($_SESSION['error'])) {
$check_email = Is_email($username);
if ($check_email) {
$sql = "SELECT * FROM agent WHERE Email= :email LIMIT 1";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':email' => $_POST['username'],
));
} else {
$sql = "SELECT * FROM agent WHERE Phone_number= :phonenumber LIMIT 1";
$stmt = $pdo->prepare($sql);
$stmt->execute(array(
':phonenumber' => $_POST['username'],
));
}
if ($stmt->execute()) {
$result = $stmt->fetch(PDO::FETCH_ASSOC);
$user = $result;
if (password_verify($password], $user['Password'])) {
//login success
$stmt->close();
$_SESSION['id'] = $user['User_id'];
$_SESSION['agentid'] = $user['agent_id'];
$_SESSION['firstname'] = $user['First_name'];
$_SESSION['Surname'] = $user['Surname'];
$_SESSION['phonenumber'] = $user['Phone_number'];
$_SESSION['email'] = $user['Email'];
$_SESSION['verified'] = $user['verified'];
// set flash message
$_SESSION['success'] = "You are now logged in! Continue with your upload";
header('location: profilepage.php');
return;
} else {
$_SESSION['errors'] = "Wrong username/password";
header('Location: register.php');
return;
}
}
}
}
instead of writing $stmt->execute() two times, store the result in a variable, and at second place use that variable.
As recommended, I've been trying to secure my DB by using prepared statements. I have the following login that works perfectly that I'm trying to convert to prepared statement.
if(isset($_POST["Submit"])) {
$Username = mysqli_real_escape_string($con, $_POST["Username"]);
$get_hash_db = mysqli_query($con, "SELECT password FROM admin_registration WHERE username='$Username'");
$hash_db_data = mysqli_fetch_array($get_hash_db);
$hash = $hash_db_data['password'];
echo $hash;
if(password_verify($_POST['Password'], $hash)){
$Password = $hash;
}else {
$_SESSION["ErrorMessage"] = "Username or Password was incorrect";
Redirect_to("admin_login.php");
}
else {
$Found_Account = Login_Attempt($Username, $Password);
$_SESSION["User_Id"] = $Found_Account["id"];
$_SESSION["Username"] = $Found_Account["username"];
if($Found_Account) {
$_SESSION["SuccessMessage"] = "Login Successful! Welcome {$_SESSION["Username"]}";
Redirect_to("blog_admin/dashboard.php");
}else {
$_SESSION["ErrorMessage"] = "Invalid Username / Password";
Redirect_to("admin_login.php");
}
}
}
Below this it takes you into a Login_Attempt() function that look like this:
function Login_Attempt($Username, $Password) {
global $con;
$sql = "SELECT * FROM admin_registration WHERE username='$Username' AND password='$Password'";
$result = mysqli_query($con, $sql);
if($admin = mysqli_fetch_assoc($result)) {
return $admin;
}
else {
return null;
}
}
With my new prepared statements I never get past $_SESSION["ErrorMessage"] = "Invalid Username / Password"; Which tells me that I'm at least satisfying the condition $Password = $hash; Here is what I have.
if(isset($_POST["Submit"])) {
$Username = mysqli_real_escape_string($con, $_POST["Username"]);
$get_hash_db = mysqli_prepare($con, "SELECT password FROM admin_registration WHERE username = ? ");
mysqli_stmt_bind_param($get_hash_db, "s", $Username);
mysqli_stmt_execute($get_hash_db);
mysqli_stmt_bind_result($get_hash_db, $hash);
mysqli_stmt_fetch($get_hash_db);
echo $hash;
if(password_verify($_POST['Password'], $hash)){
$Password = $hash;
}else {
$_SESSION["ErrorMessage"] = "Username or Password was incorrect";
Redirect_to("admin_login.php");
}
Once I get passed this, I'm going through this:
else {
$Found_Account = Login_Attempt($Username, $Password);
$_SESSION["User_Id"] = $Found_Account["id"];
$_SESSION["Username"] = $Found_Account["username"];
if($Found_Account) {
$_SESSION["SuccessMessage"] = "Login Successful! Welcome {$_SESSION["Username"]}";
Redirect_to("blog_admin/dashboard.php");
}else {
$_SESSION["ErrorMessage"] = "Invalid Username / Password";
Redirect_to("admin_login.php");
}
}
}
but it always returns to $_SESSION["ErrorMessage"] = "Invalid Username / Password"; I'm not sure I understand why? Is it because I'm binding the param $Username, so function Login_Attempt($Username, $Password) does not handle correctly? Sorry, this is my first go at prepared statements so really struggling to understand.
ok so ive got password_hash working on one of my pages.
I'm wondering how would i apply password_verify to the following code:
function selectUser($conn, $username, $password)
{
$query = "SELECT username, password FROM login WHERE password = :password AND username = :username";
$stmt = $conn->prepare($query);
$stmt->bindValue(':username', $username);
$stmt->bindValue(':password', $password);
$stmt->execute();
if ($row = $stmt->fetch()) {
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
echo "Welcome, you are now logged in as " . $username;
return true;
}
else {
//echo "Your details were not found";
return false;
}
tried it myself and its been very confusing to me.
thank you
also got this:
if(!isset($_POST["Login"]))
{
header("Location:new-user.php");
}
$username=trim($_POST['username']);
$password=$_POST['password'];
$username= htmlspecialchars($username);
$validForm = true;
if (empty($_POST["username"]))
{
$validForm=false;
}
if (empty($_POST["password"]))
{
$validForm=false;
}
if (!$validForm) {
$error = "please ensure all fields are filled in";
include("add.php");
return false;
}
$conn=getConn();
$successLogin=selectUser($conn,$username,$password);
if($successLogin)
{
header( "Location: search.php" );
}else{
$error = "The details you have entered are incorrect";
include("add.php");
}
$conn=NULL; //close the connection
Update
also tried this: Knowing this doesnt work, tested with echo statements but still no luck
function hash_input() {
$password = "sfafgsd";
return $password = password_hash($_POST['password'], PASSWORD_BCRYPT);
}
function selectUser($conn, $username, $password)
{
$query = "SELECT password FROM login WHERE username = :username";
$stmt = $conn->prepare($query);
$stmt->bindValue(':username', $username);
$stmt->execute();
echo $username . " " . $password;
if ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
echo "WE MADE IT";
if(password_verify(hash_input($password), $row['password'])){
$_SESSION['username'] = $username;
echo "Welcome, you are now logged in as " . $username;
return true;
}
//echo "Your details were not found";
sleep(1);
return false;
}
else
{
//echo "Your details were not found";
return false;
}
}
The comments given by Mark cover the below exactly.
Order of events:
Send username to database and collect the hashed password from the row found.
run the password string given through password_verify to compare with the hashed value
return this result (true/false).
Celebrate. Have a coffeee or a tea.
There is no need to $_SESSION password data and this is a bad idea. Password data (hash or plaintext) should not be retained beyond this function call. If you do for some reason need to have a nonce value associated with this account/membership/login then this should be setup using a random string in its own column in the database.
Improved Function Code
function selectUser($conn, $username, $password)
{
$query = "SELECT password FROM login WHERE username = :username LIMIT 1";
$stmt = $conn->prepare($query);
$stmt->bindValue(':username', $username);
// $stmt->bindValue(':password', $password); NO Don't do this.
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_ASSOC))
{
if(password_verify($password,$row['password'])){
$_SESSION['username'] = $username;
// $_SESSION['password'] = $password; DO NOT DO THIS
echo "Welcome, you are now logged in as " . $username;
return true;
}
//bad password
//echo "Your details were not found";
sleep(1); // it can be a good idea to add a forced pause on
// password fail to discourage brute force cracking.
return false;
}
//echo "Your details were not found";
return false;
}
We are using below code for "sign up". we have only password field , we want to add confirm password field.
signup.php
if(isset($_POST['btn-signup']))
{
$uname = trim($_POST['txtuname']);
$email = trim($_POST['txtemail']);
$upass = trim($_POST['txtpass']);
$code = md5(uniqid(rand()));
$stmt = $reg_user->runQuery("SELECT * FROM tbl_users WHERE userEmail=:email_id");
$stmt->execute(array(":email_id"=>$email));
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($stmt->rowCount() > 0)
{
$msg = "
email allready exists
";
}
else
{
if($reg_user->register($uname,$email,$upass,$code))
{
$id = $reg_user->lasdID();
$key = base64_encode($id);
$id = $key;
$message = "
some message";
$subject = "Confirm Registration";
$reg_user->send_mail($email,$message,$subject);
$msg = "
some message
";
}
else
{
echo "sorry , Query could no execute...";
}
}
}
class.usr.php
public function register($uname,$email,$upass,$code)
{
try
{
$password = md5($upass);
$stmt = $this->conn->prepare("INSERT INTO tbl_users(userName,userEmail,userPass,tokenCode)
VALUES(:user_name, :user_mail, :user_pass, :active_code)");
$stmt->bindparam(":user_name",$uname);
$stmt->bindparam(":user_mail",$email);
$stmt->bindparam(":user_pass",$password);
$stmt->bindparam(":active_code",$code);
$stmt->execute();
return $stmt;
}
catch(PDOException $ex)
{
echo $ex->getMessage();
}
}
I tried adding below code, but it did't worked for me.
$cpass = trim($_POST['txtpass']);
/* Afer if statement */
elseif($pass != $cpass){
$msg = "passwords doesn't match";
}
also tried in class.usr.php file, but no luck.....
First of all you have not mentioned confirm password field.
Lets assume your confirm password field is "txtConfirmPass"
Before redirect to register function need to check password and confirm password like
$upass = trim($_POST['txtpass']);
$uConfirmPass = trim($_POST['txtConfirmPass']);
if($upass != $uConfirmPass){
// Password not match your code here
}else{
if($reg_user->register($uname,$email,$upass,$code)){
$id = $reg_user->lasdID();
$key = base64_encode($id);
$id = $key;
$message = "some message";
$subject = "Confirm Registration";
$reg_user->send_mail($email,$message,$subject);
$msg = "some message";
}
else
{
echo "sorry , Query could no execute...";
}
}
Hopefully it help you out.
I'm hashing a password using sha1 and it is successfully storing it in the database, however i cannot seem to properly check to see if the sha1 matches one that is in the database. I've tried numerous different iterations of the below code, but nothing seems to work - what am i missing?
Registration
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$passwordEncrypted = sha1($password);
try {
$result = $db->prepare("INSERT INTO
user_info
SET
username = :user,
pass = :pass
");
$result->bindParam(':user', $username);
$result->bindParam(':pass', $passwordEncrypted);
$result->execute();
}
catch (Exception $e) {
echo "Could not create username";
}
if (isset($_POST['submit'])) {
foreach ($_POST as $field) {
if (empty($field)) {
$fail = true;
}
else {
$continue = false;
}
}
if ($field == $fail) {
echo "You must enter a username and/or password";
}
else {
echo "Your account has been successfully created.";
}
}
?>
Logging in
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$encryptedPassword = sha1($password);
try {
$result = $db->prepare("SELECT username, pass FROM user_info WHERE username = :user AND BINARY pass = :pass");
$result->bindParam(':user', $username);
$result->bindParam(':pass', $password);
$result->execute();
$rows = $result->fetch(PDO::FETCH_NUM);
}
catch (Exception $e) {
echo "Could not retrieve data from database";
exit();
}
if ($rows) {
session_start();
$_SESSION['username'] = $_POST['username'];
$_SESSION['loggedin'] = true;
include("inc/redirect.php");
} else {
if (isset($_POST['login'])) {
echo "Username or password incorrect (passwords are case sensitive)";
}
}
?>
You need to hash the password before querying the table, not afterwards:
<?php
$username = $_POST['username'];
$password = $_POST['password'];
$passwordEncrypted = sha1($password);
try {
$result = $db->prepare("SELECT username, pass FROM user_info WHERE username = :user AND BINARY pass = :pass");
$result->bindParam(':user', $username);
$result->bindParam(':pass', $passwordEncrypted);
$result->execute();
if ($result->fetch(PDO::FETCH_NUM)) {
session_start();
$_SESSION['username'] = $_POST['username'];
$_SESSION['loggedin'] = true;
include("inc/redirect.php");
} else {
if (isset($_POST['login'])) {
echo "Username or password incorrect (passwords are case sensitive)";
}
}
}
catch (Exception $e) {
echo "Could not retrieve data from database";
exit();
}
?>