Ive tried to make a user profile where they can change name email and password. Everything is ok instead the password will not work. This is the update sql
if(isset($_POST['update_password'])){
if ($_POST["currentPassword"] == $row["password"]) {
mysqli_query($con, "UPDATE users set password='" . $_POST["newPassword"] . "' WHERE id='$userid'");
$message = "Password Changed";
} else {
$message = "Current Password is not correct";
}
}
this is the form
<div >
<h2><i ></i> Change Password</h2>
<form name="pwdChange" method="post" action="">
<?php if(isset($message)) { echo $message; } ?>
<table width="100%">
<tr>
<td>Current Password</td>
<td><input type="password" name="currentPassword" /><span id="currentPassword" ></span></td>
</tr>
<tr>
<td>New Password</td>
<td><input type="password" name="newPassword" /><span id="newPassword" ></span></td>
</tr>
<td>Confirm Password</td>
<td><input type="password" name="confirmPassword" /><span id="confirmPassword" ></span></td>
</tr>
</table>
<button name="update_password">Change password</button>
</form>
</div>
and I know in mysql the table shows like this under password
$2y$10$K.IlGbu64Jwzm0EzeTcQzu.N0uGGK93hGqY9mGg1.75uMWtKIKYOy
How can I get this to solved it?
CodePudding user response:
I made the db for testing as follows:
mysql> show columns from users;
---------- -------------- ------ ----- --------- -------
| Field | Type | Null | Key | Default | Extra |
---------- -------------- ------ ----- --------- -------
| password | varchar(255) | YES | | NULL | |
| id | int | YES | | NULL | |
---------- -------------- ------ ----- --------- -------
2 rows in set (0,00 sec)
mysql> INSERT INTO users values ('$2y$10$lO5oVXCXN5npiCc1Eq2aIOwHudDyqRpFl9VMw0VDleyYBYY01n26e',1);
mysql> select * from users;
-------------------------------------------------------------- ------
| password | id |
-------------------------------------------------------------- ------
| $2y$10$lO5oVXCXN5npiCc1Eq2aIOwHudDyqRpFl9VMw0VDleyYBYY01n26e | 1 |
-------------------------------------------------------------- ------
1 row in set (0,00 sec)
$2y$10$lO5oVXCXN5npiCc1Eq2aIOwHudDyqRpFl9VMw0VDleyYBYY01n26e
is test123
so your current password will be test123
A working code for what you're attempting to do is the following but WARNING This code is vulnerable to sql injection as I described in my comment. In order to avoid more complex stuff and to let you to understand the basics I followed your example but take a look at prepared statements when you have done with this. https://www.php.net/manual/en/mysqli.quickstart.prepared-statements.php Also, follow my todo to make a better work with your code.
<?php
$con = new mysqli("127.0.0.1", "root", "test", "test", 3306); //change this with your connection
// Tested on php 7.4
if ($con->connect_errno) {
echo "Failed to connect to MySQL: " . $con->connect_error;
exit();
}
$userId = 1; //TODO: change this and make a select for the id with username, something like SELECT id from users where username = "yourusername";
$sql = "SELECT password from users where id = " . $userId;
$result = $con->query($sql);
$rows = $result->fetch_array();
$passwordFromDB = $rows['password'];
if (isset($_POST['update_password'])) {
if ($_POST["newPassword"] !== $_POST["confirmPassword"]) {
die("Password and its confirmation do not match");
}
//TODO: you should also consider to check that the new password should be different from the old one. You need also to do a check on passwords lengths
if (password_verify($_POST["currentPassword"], $passwordFromDB)) {
$newPassword = password_hash($_POST["newPassword"], PASSWORD_BCRYPT); //TODO: you should make a check for the password length because bcrypt truncates password to 72 bytes
$query = "UPDATE users set password='" . $newPassword . "' WHERE id='$userId'";
$res = mysqli_query($con, $query);
//echo "OK: ".$res;
if ($res) {
die("Password Changed");
}
} else {
die("Current Password is not correct");
}
}
?>
<div >
<h2><i ></i> Change Password</h2>
<form name="pwdChange" method="post" action="">
<?php if (isset($message)) {
echo $message;
} ?>
<table width="100%">
<tr>
<td>Current Password</td>
<td><input type="password" name="currentPassword" /><span id="currentPassword" ></span></td>
</tr>
<tr>
<td>New Password</td>
<td><input type="password" name="newPassword" /><span id="newPassword" ></span></td>
</tr>
<td>Confirm Password</td>
<td><input type="password" name="confirmPassword" /><span id="confirmPassword" ></span></td>
</tr>
</table>
<button name="update_password">Change password</button>
</form>
</div>
CodePudding user response:
@Virgula this is my full profile.php
<?php
$con = mysqli_connect("localhost","root","*********","dbcomment") or die("Error in database connection");
// We need to use sessions, so you should always start sessions using the below code.
session_start();
$userid = $_SESSION['id'];
$query = mysqli_query($con,"SELECT * FROM users where id='$userid'")or die(mysqli_error());
$row = mysqli_fetch_array($query);
$passwordFromDB = $row['password'];
if(isset($_POST['update_profile'])){
$username = $_POST['username'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$result = mysqli_query($con,"UPDATE users SET username='$username',email='$email',phone='$phone' WHERE id='$userid'");
if($result) {
header("location:profile.php");
} else {
echo 'Something went wrong';
}
}
if(isset($_POST['update_password'])){
if ($_POST['currentPassword'] !== $_POST["confirmPassword"]) {
die("Password and its confirmation do not match");
if (password_verify($_POST["currentPassword"], $passwordFromDB)) {
$newPassword = password_hash($_POST["newPassword"], PASSWORD_BCRYPT); //TODO: you should make a check for the password length because bcrypt truncates password to 72 bytes
$query = "UPDATE users set password='" . $newPassword . "' WHERE id='$userid'";
$res = mysqli_query($con, $query);
if ($res) {
die("Password Changed");
}
} else {
die("Current Password is not correct");
}
}
}
// mysqli_query($con, "UPDATE users set password='" . $_POST["newPassword"] . "' WHERE id='$userid'");
// $message = "Password Changed";
// } else {
// $message = "Current Password is not correct";
// }
// }
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<script src="jquery-3.2.1.min.js"></script>
<script src='https://kit.fontawesome.com/114db57c0a.js' crossorigin='anonymous'></script>
<script>
function validatePassword() {
var currentPassword,newPassword,confirmPassword,output = true;
currentPassword = document.frmChange.currentPassword;
newPassword = document.frmChange.newPassword;
confirmPassword = document.frmChange.confirmPassword;
if(!currentPassword.value) {
currentPassword.focus();
document.getElementById("currentPassword").innerHTML = "Current password required";
output = false;
}
else if(!newPassword.value) {
newPassword.focus();
document.getElementById("newPassword").innerHTML = "required";
output = false;
}
else if(!confirmPassword.value) {
confirmPassword.focus();
document.getElementById("confirmPassword").innerHTML = "required";
output = false;
}
if(newPassword.value != confirmPassword.value) {
newPassword.value="";
confirmPassword.value="";
newPassword.focus();
document.getElementById("confirmPassword").innerHTML = "Password does not match";
output = false;
}
return output;
}
</script>
<style>
* {
box-sizing: border-box;
}
.safe_profile {
background: linear-gradient(to bottom, #3399ff 0%, #33ccff 100%);
border-radius: 10px;
border: 0px solid black;
padding: 1em 2em;
float: right;
}
.survey{
background-color: white;
padding: 1em 2em;
text-align: left;
border-radius: 25px;
border: 1px solid black;
}
.surveygrid {
display: grid;
grid-column-gap: 20px;
grid-template-columns: repeat(1, 1fr);
}
.column {
background-color: white;
padding: 1em 2em;
text-align: left;
border-radius: 25px;
border: 1px solid black;
}
.grid {
display: grid;
grid-column-gap: 20px;
grid-template-columns: repeat(3, 1fr);
}
/* Responsive layout - when the screen is less than 600px wide, make the three columns stack on top of each other instead of next to each other */
@media screen and (max-width: 400px) {
.survey {
width: 100%;
}
}
</style>
</head>
<body>
<div >
<div >
<h2><i ></i> My Profile - ID N°: <?php echo $row['id']; ?></h2>
<form method="post" enctype='multipart/form-data' action="">
<table style="width: 100%">
<tr>
<td><i ></i></td><td style="float: left">Name </td><td><input type="text" name="username" value="<?php echo $row['username']; ?>" placeholder="Enter your name"></td>
</tr>
<tr>
<td><i ></i></td><td style="float: left">E-mail </td><td><input type="email" name="email" value="<?php echo $row['email']; ?>" placeholder="Enter your email"></td>
</tr>
<tr>
<td><i ></i></td><td style="float: left">Phone </td><td><input type="tel" name="phone" value="<?php echo $row['phone']; ?>" placeholder="Enter your phone number"></td>
</tr>
</table>
<button name="update_profile">Save Profile</button>
</form>
</div>
<div >
<h2><i ></i> Change Password</h2>
<form name="frmChange" method="post" action="" onSubmit="return validatePassword()">
<?php if(isset($message)) { echo $message; } ?>
<span style="color: red; margin: auto;" id="currentPassword" ></span>
<span style="color: red; margin: auto;" id="newPassword" ></span>
<span style="color: red; margin: auto;" id="confirmPassword" ></span>
<table width="100%">
<tr>
<td>Current Password</td>
<td><input type="password" name="currentPassword" /></td>
</tr>
<tr>
<td>New Password</td>
<td><input type="password" name="newPassword" /></td>
</tr>
<td>Confirm Password</td>
<td><input type="password" name="confirmPassword" /></td>
</tr>
</table>
<button name="update_password">Change password</button>
</form>
</div>
</div>
</body>
</html>
And what you postet before me about Password is not test123 because its has 12 digits Password from A-Z a-z 0-9 and my sql is I have is
CREATE TABLE `users` (
`id` int(11) NOT NULL,
`username` varchar(50) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(100) NOT NULL,
`phone` varchar(25) NOT NULL DEFAULT '0',
`create_datetime` datetime NOT NULL,
`activation_code` varchar(50) DEFAULT '',
`ip` varchar(45) NOT NULL DEFAULT '0'
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
--
-- Dumping data for table `users`
--
INSERT INTO `users` (`id`, `username`, `password`, `email`, `phone`, `create_datetime`, `activation_code`, `ip`) VALUES
(1, 'Christian', '$2y$10$U9CQio6KIMSRTNwGC3yKbOC4icFY65RM06tUwo.T4APWDVEk4RJwy', 'c********@******.***', ' *********', '2022-07-14 12:28:13', 'activated', '***.***.***.***'),
(2, 'AnaBell', '$2y$10$K.IlGbu64Jwzm0EzeTcQzu.N0uGGK93hGqY9mGg1.75uMWtKIKYOy', 'c*********@***.***', ' **********', '2022-07-17 16:25:56', 'activated', '***.***.***.***');
--
-- Indexes for dumped tables
--
--
-- Indexes for table `users`
--
ALTER TABLE `users`
ADD PRIMARY KEY (`id`);
--
-- AUTO_INCREMENT for dumped tables
--
--
-- AUTO_INCREMENT for table `users`
--
ALTER TABLE `users`
MODIFY `id` int(11) NOT NULL AUTO_INCREMENT, AUTO_INCREMENT=3;
Is the backup from my SQL. I just exchange the private details in ****** and this is what is look like right now. About sql injection I don't know really about it because I'm just new with PHP 8 etc.
I just restarted website again about 3 weeks ago after 10 years of break time.