Change password not working php - php

Can you please help me what is wrong with my code? I cannot seem to find the error. My problem is that the new password is not saving in my database. I cannot log in with my new password.
This is my php code.
<?php
session_start();
$uid = $_SESSION["uid"];
if($uid)
{
//user is logged in
if(isset($_POST["changepwbtn"]))
{
// check fields
$oldpw = $_POST['old_pw'];
$newpw = $_POST['new_pw'];
$renewpw = $_POST['c_npw'];
//check pw db
$sql = "SELECT pazzword FROM customer_info where user_id = '$uid'";
$run_query = mysqli_query($con,$sql);
$row = mysqli_fetch_array($run_query);
$oldpwdb = $row['pazzword'];
//check pw
if($oldpw==$oldpwdb)
{
//check two new pw
if($newpw==$renewpw)
{
$query_change = mysql_query("UPDATE customer_info SET pazzword = '$newpw' WHERE user_id = '$uid'");
session_destroy();
die("Your password has been changed! <a href='index.php'>Return</a>");
}
else
die("New passwords doesn`t match!");
}
else
die("Old password doesn`t match");
}
echo" ";
}
else
die("You need to log in!");
?>

you have to pass the connection object to mysqli_query
$query_change = mysqli_query($con, "UPDATE customer_info SET pazzword = '$newpw' WHERE user_id = '$uid'");

Related

Login Attempt 3 times and Redirect to forgot password

if(isset($_POST['submit'])){
$username = escape_string($_POST['username']);
$password = escape_string($_POST['password']);
$query = query("SELECT 'username', 'upassword' FROM userregistration WHERE username = '{$username}' AND upassword = '{$password }' ");
confirm($query);
if(mysqli_num_rows($query) == 0) {
set_message("Your Password or Username are wrong");
redirect("login1.php");
} else {
$_SESSION['username'] = $username;
redirect("index.php");
}
}
This is my Log In Condition in my Log In form. This is working. but im confused how to add some conditions that redirects the user to other form after attempting to login 3 times.
you need to create new session veriable for check attempt when veriable equal to 3 attempt it will redirect you
<?php
if(isset($_POST['submit'])){
$username = escape_string($_POST['username']);
$password = escape_string($_POST['password']);
$query = query("SELECT 'username', 'upassword' FROM userregistration WHERE username = '{$username}' AND upassword = '{$password }' ");
confirm($query);
if(mysqli_num_rows($query) == 0) {
set_message("Your Password or Username are wrong");
// simple create session here..
if(isset($_SESSION['forget'])){
$_SESSION['forget']++;
if($_SESSION['forget'] == 3){
//redirect( forget page);
}
}else{
$_SESSION['forget'] = 0;
}
redirect("login1.php");
} else {
$_SESSION['username'] = $username;
redirect("index.php");
}
}
?>

how to retrieve MD5 password

I've put username and md5(password) on my MySQL database. Below is my old login PHP code. I want to add some code that can retrieve my md5 password, because on my old code there is no md5 password. Where is should I add md5(password)?
Here is my full login code:
<?
if ($_POST['username']) {
$username=trim($_POST['username']);
$username = mysql_real_escape_string($username);
$password=trim($_POST['password']);
$password=mysql_real_escape_string($password);
//$password = hash('md5','$password');
if ($password==NULL) {
header("Location: login.php?error=2");
}else{
if($_POST['code']!=$_SESSION['string']){
header("Location: login.php?error=1");
}else{
$query = mysql_query("SELECT username,password FROM tb_users WHERE username = '$username'") or die(mysql_error());
if(mysql_num_rows($query) == 0)
{
header("Location: login.php?error=3");
} else {
$data = mysql_fetch_array($query);
if($data['password'] != $password) {
header("Location: login.php?error=4");
}else{
$query = mysql_query("SELECT username,password FROM tb_users WHERE username='$username' ") or die(mysql_error());
$row = mysql_fetch_array($query);
$nicke=$row['username'];
$passe=$row['password'];
setcookie("usNick",$nicke,time()+36000);
setcookie("usPass",$passe,time()+36000);
$lastlogdate=time();
$lastip = getRealIP();
$querybt = "UPDATE tb_users SET lastlogdate='$lastlogdate', lastiplog='$lastip' WHERE username='$nicke'";
mysql_query($querybt) or die(mysql_error());
$query = mysql_query("SELECT akhirupgrade from tb_upgrade WHERE username = '$username' and status='upgraded'") or die(mysql_error());
if(mysql_num_rows($query) > 0) {
$row = mysql_fetch_array($query);
$akhir=$row["akhirupgrade"];
$tgl=time();
if ($tgl > $akhir) {
$query = mysql_query("update tb_upgrade set status='', date='', paket='', akhirupgrade='' WHERE username='$username' and status='upgraded'");
$query = mysql_query("update tb_users set account='' WHERE username='$username'");
}
}
header("Location: member.php");
}
}
}
}
}
?>
I would use password_hash() if you running on php 5.5 or greater
When you send the password to the database simply hash it with the function
$password = password_hash(filter_input(INPUT_POST, "password"));
The when you pull the password back out of the database do the same thing to the password they submitted.
$passwordFromDb = $result['password']; //Password from the database
$passwordFromLoginForm = password_hash(filter_input(INPUT_POST, "password");
//Then when youve got the password to check it agaisnt there input
if($passwordFromDb === $passwordFromForm){
//The password they entered was the same as the password in the database
} else {
//The password was wrong
}
I have not tested this code so there may be errors but hopefully youll get the point :)
PS dont use MD5 please, Very insecure
If you must use md5
$password = md5(filter_input(INPUT_POST, "password"));//Store password
$passwordFromDb = $result['password']; //Password from the database
$passwordFromLoginForm = md5(filter_input(INPUT_POST, "password");
//Then when youve got the password to check it agaisnt there input
if($passwordFromDb === $passwordFromForm){
//The password they entered was the same as the password in the database
} else {
//The password was wrong
}

Updated: Store the logged in attempts in database using PHP

I try to store the logged in attempts in the database, but it's not working. The loginAttempt columns is not updating. Also, I want to count the login attempts and block the user after 3 attempts.
How to fix this?
Here's the script:
session_start();
$loginDate = date("Y-m-d H:i:s");
$Error ="";
$successMessage ="";
if (isset($_POST['submit'])){
if ( !( $_POST['cnumber'] == "" && $_POST['password'] == "")){
$cnumber=$_POST['cnumber'];
$password= sha1($_POST['password']);
$cnumber = filter_var($cnumber, FILTER_SANITIZE_NUMBER_INT);
if (filter_var($cnumber, FILTER_VALIDATE_INT)){
$con=mysqli_connect("localhost","test","password","login");
$result = mysqli_query($con, "SELECT * FROM Users WHERE contractNumber='$cnumber' AND password='$password'");
$data = mysqli_num_rows($result);
if($data==1){
$_SESSION['login_user']=$cnumber;
mysqli_query($con, "INSERT INTO `homecre1_testemailCheck`.`Logs`(`contractNumber`, `lastLogin`) VALUES ('$cnumber', '$loginDate')");
header('Location: profile.php');
} else {
mysqli_query($con, "UPDATE Logs SET loginAttempt = loginAttempt+1 WHERE contractNumber = '$cnumber'");
}
mysqli_close($con);
} else {
$Error ="Invalid Contract Number.";
}
} else {
$Error ="Contract Number or Password is Empty.";
}
Here's my database structure:
Users - table
id -PK
contractNumber
email
password
Logs - table
userId
contractNumber
lastLogin
loginAttempt
Your update query is missing SET and column contarct_number might be wrong: Your query should be like:
mysqli_query($con, "UPDATE Logs SET loginAttempt = loginAttempt+1
WHERE contractNumber = '$cnumber'");

Display error message PHP Mysql

i am unable to get the last 2 echos to work, even if the update query fails it still displays success. If anyone has any suggestions on this code to be improved on any line, please do!
<?php
if(!empty($_POST['username']) && !empty($_POST['answer'])) {
$username = $_POST['username'];
$idfetch = mysql_query("SELECT id FROM users WHERE username ='$username'") //check it
or die(mysql_error());
$fetched = mysql_fetch_array($idfetch);
$id = $fetched['id']; //get users id for checking
$answer = $_POST['answer'];
$password = (mysql_real_escape_string($_POST['password']));
$confpass = (mysql_real_escape_string($_POST['confpass']));
if ($password != $confpass) {
echo ("Passwords do not match, please try again.");
exit;
}
$updatequery = mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'");
if($updatequery) {
echo "<h1>Success</h1>";
echo "<p>Your account password was successfully changed. Please click here to login.</p>";
}
else {
echo "<h1>Error</h1>";
echo "<p>Sorry, but a field was incorrect.</p>";
}
}
?>
Thanks in advance!
mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'") or die(mysql_error()."update failed");
and use
mysql_affected_rows()
Returns the number of affected rows on success, and -1 if the last query failed.
use try catch and try to get the error enable error reporting in php also
<?php
error_reporting(E_ALL);
ini_set('display_errors','On');
if(!empty($_POST['username']) && !empty($_POST['answer'])) {
$username = $_POST['username'];
$idfetch = mysql_query("SELECT id FROM users WHERE username ='$username'") //check it
or die(mysql_error());
$fetched = mysql_fetch_array($idfetch);
$id = $fetched['id']; //get users id for checking
$answer = $_POST['answer'];
$password = (mysql_real_escape_string($_POST['password']));
$confpass = (mysql_real_escape_string($_POST['confpass']));
if ($password != $confpass) {
echo ("Passwords do not match, please try again.");
exit;}
try{
$updatequery = mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'");
if($updatequery) {
echo "<h1>Success</h1>";
echo "<p>Your account password was successfully changed. Please click here to login.</p>"; }
else {
echo "<h1>Error</h1>";
echo "<p>Sorry, but a field was incorrect.</p>";
}
}catch(Exception $e){
print_R($e);
}
}
use or die(mysql_error()) as it will display mysql error if there is an error with your query.
$updatequery = mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'") or die(mysql_error());
Try this:
$idfetch = mysql_query("SELECT id FROM users WHERE username ='$username'");
if(!idfetch){
die(mysql_error());
}
Do the same for all other queries too.
try this, first count the row count value its great 1 then proceed the login process.
<?php
if(!empty($_POST['username']) && !empty($_POST['answer'])) {
$username = $_POST['username'];
$idfetch = mysql_query("SELECT id FROM users WHERE username ='$username'") //check it
or die(mysql_error());
$fetched = mysql_fetch_array($idfetch);
$count= mysql_num_rows($idfetch);
if($count>0){
$id = $fetched['id']; //get users id for checking
$answer = $_POST['answer'];
$password = (mysql_real_escape_string($_POST['password']));
$confpass = (mysql_real_escape_string($_POST['confpass']));
if ($password != $confpass) {
echo ("Passwords do not match, please try again.");
exit;
}
$updatequery = mysql_query("UPDATE users SET PASSWORD='$password' WHERE id='$id' AND username='$username' AND answer='$answer'");
if($updatequery) {
echo "<h1>Success</h1>";
echo "<p>Your account password was successfully changed. Please click here to login.</p>";
}
else {
echo "<h1>Error</h1>";
echo "<p>Sorry, but a field was incorrect.</p>";
}
} } ?>
Use
if(mysql_num_rows($updatequery) > 0) {
// success
} else {
// error
}
$updatequery will always be true (not NULL), until there is an error in your query

PHP Session not holding values

After a good few hours of looking at posts and different forums I finally give up.
I have been learning PHP for the last 24 hours by trying to create a registration and a login page.
Registration seems to be working (I am sure that there are some bugs etc, but as of right now everything seems to be in sql).
As far as my login page, this is where I am having some problems.
NEW EDIT
Here is my registration.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
//Set error msg to blank
$errorMsg = "";
// Check to see if the form has been submitted
if (isset($_POST['username']))
{
include_once 'db_connect.php';
$username = preg_replace('/[^A-Za-z0-9]/', '', $_POST['username']);
$password = preg_replace('/[^A-Za-z0-9]/', '', $_POST['password']);
$accounttype = preg_replace('/[^A-Za-z]/','', $_POST['accounttype']);
$email = filter_var($_POST['email'], FILTER_VALIDATE_EMAIL);
//validate email with filter_var
if ((!$username) || (!$password) || (!$accounttype) || (!$email))
{
$errorMsg = "Everything needs to be filled out";
}
else {
// if fields are not empty
// check if user name is in use
$db_username_check = mysql_query("SELECT id FROM members WHERE username='$username' LIMIT 1");
$username_check = mysql_num_rows($db_username_check);
// check if email is in use
$db_email_check = mysql_query("SELECT id FROM members WHERE email='$email' LIMIT 1");
$email_check = mysql_num_rows($db_email_check);
//if username is in use ... ERROR
if ($username_check > 0) {
$errorMsg = "ERROR: username is already in use";
// if username is ok check if email is in use
} else if ($email_check > 0) {
$errorMsg = "ERROR: email is already in use";
} else {
session_start();
$hashedPass = md5($password);
// Add user info into the database table, claim your fields then values
$sql = mysql_query("INSERT INTO members (username, password, email, accounttype )
VALUES('$username', '$hashedPass', '$email', '$accounttype')") or die (mysql_error());
// Retrieves the ID generated for an AUTO_INCREMENT column by the previous query
$id = mysql_insert_id();
$_SESSION['id'] = $id;
mkdir("members/$id", 0755);
header("location: member_profile.php?id=$id");
$errorMsg = "Registration Successful";
exit();}
}
// if the form has not been submitted
} else { $errorMsg = 'To register please fill out the form'; }
?>
here's my Login.php
<?php
error_reporting(E_ALL);
ini_set('display_errors', '1');
// if the form has been submitted
$errorMsg = "";
if ($_POST['username']){
include_once('db_connect.php');
$username = stripslashes($_POST['username']);
$username = strip_tags($username);
$username = mysql_real_escape_string($_POST['username']);
$password = mysql_real_escape_string($_POST['password']);
$hashedPass = md5($password);
$sql = "SELECT username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
$login_check = mysql_query($sql);
$count = mysql_num_rows($login_check);
$row = mysql_fetch_array($login_check);
//var_dump($id, $username, $password);
if($count==1)
{
session_start();
//$id = $row["id"];
// $_SESSION['id'] = $userid;
// $username = $row['username'];
// $_SESSION['username'] = $username;
// header("location: member_profile.php?id=$userid");
echo "User name OK";
return true;
} else {
echo "Wrong username or password";
return false;
}
}
?>
Whenever someone registers $id = mysql_insert_id();will pull the ID from the last query and start a $_SESSION['id']. However during a login right after if($count==1) I am completely lost. For some reason the name and the password is checked and does go through but the ID fails.
I did try adding "SELECT id FROM members WHERE id='$id'" but my $id is always undefined.
My member_profile.php is something like this:
<?php
session_start();
$toplinks = "";
if(isset($_SESSION['id'])) {
//If the user IS logged in show this menu
$userid = $_SESSION['id'];
$username = $_SESSION['username'];
$toplinks = '
Profile •
Account •
Logout
';
} else {
// If the user IS NOT logged in show this menu
$toplinks = '
JOIN •
LOGIN
';
}
?>
Thank you to everyone for any tips as far as security, structure and coding style. This is day #3 of php for me.
Please excuse any errors.
Your if is going inside comments check this --
<?php // if the form has been submitted $errorMsg = ""; if
edit it --
<?php
// if the form has been submitted
$errorMsg = "";
if(($_POST['username']) && ($_POST['password'])){
You are using mysql and using mysqli in your code too--
$row = mysqli_fetch_array($sql);
use --
$row = mysql_fetch_array($sql);
Look at your sessions as well as Phil mentioned in comments.
session_start()
Replace the code
$row = mysqli_fetch_array($sql); to $row = mysql_fetch_array($login_check);
if($count==1)
{
$id = $row['id'];
session_start();
$_SESSION['id'] = $id;
//$row = mysqli_fetch_array($sql);
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
exit();
} else {
echo "Wrong username or password";
return false;
}
Also Change your query if you have any id field in table:
$sql = "SELECT id,username,password FROM members WHERE username ='$username' AND password = '$hashedPass'";
First I went over the code. Since this is my day #4 of php, I started changing everything from mysql to mysqli which made a little more sense to me. The code is probably still messy but it does work so far. Thank you
$sql = ("SELECT * FROM members WHERE username = '$username' && password = '$hashedPass'");
$login_check = mysqli_query($link, $sql);
$count = $login_check->num_rows;
$row = mysqli_fetch_array($login_check);
printf("Result set has %d rows.\n", $count);
if($count==1)
{
session_start();
$id = $row["id"];
$_SESSION['id'] = $id;
$username = $row['username'];
$_SESSION['username'] = $username;
header("location: member_profile.php?id=$id");
echo "User name OK";
return true;

Categories