I create a function to edit user password here the function code.
function updateUser ()
{
$current = md5($_POST['cpassword']);
$new = md5($_POST['npassword']);
$newc = md5($_POST['npasswordc']);
$name = $_POST['username'];
connectDB();
$check = mysql_query("SELECT password FROM user WHERE user_name = '$name'")
or die(mysql_error());
if ($check != $current) {
?> <div id="error">
<?php die('Current password is wrong. Press back to try again.'); ?>
</div> <?php
}
if ($new == $newc) :
$sql = "UPDATE user SET password = '$new' WHERE user_name = '$name'";
execute($sql);
?> <div id="error">
<?php die('Password Successfully Updated. Back to dashboard');
?> </div> <?php
else : ?> <div id="error">
<?php die('New Password did not match. Press back to try again');
?> </div> <?php
endif;
}
the value will be pass by the form on different page, everything seem to work fine. When I try to change password, it say successful, and when I check in the database, the md5 value is changing that mean the password was change.
But when I try to change password of same username, I still need to enter the old password for current password, even though in database it already changed?
What seem to be the problem?
Thank you
$check is a mysql resource, not a value. You might do
if($check && (mysql_num_rows($check) > 0))
{
$res = mysql_fetch_assoc($check);
if($res['password'] != $current) {
Be careful of SQL injections, you should do at least
$name = mysql_real_escape_string($_POST['username']);
before entering it into the query.
Also, md5 is a week hashing algorithm, I strongly suggest you use a SALT, and better hash algos like at the very least sha1() or better go for the sha2 family (sha256, sha512, for ex) or bcrypt
I have changed your code... maybe it works. also watch the comments it explains something maybe it helps:
function updateUser ()
{
$current = md5($_POST['cpassword']);
$new = md5($_POST['npassword']);
$newc = md5($_POST['npasswordc']);
// first check if the passwords matches if not why waist the connection
if ($new == $newc) {
$name = $_POST['username'];
connectDB();
// why not checking your pass in the query
// when a result is zero it means there is no match found
$check = mysql_query("SELECT password FROM user WHERE user_name = '{$name}' AND password = '{$current}'") or die(mysql_error());
$result = mysql_fetch_assoc($check);
// You where checking a resource with a string(MD5)?
if (mysql_num_rows($check) == 0) {
?><div id="error">
<?php die('Current password is wrong. Press back to try again.'); ?>
</div><?php
return false;
} else {
// update the query with the ID you got from the check..
// why? because a ID is always unique
$sql = "UPDATE user SET password = '{$new}' WHERE user_id = '{$result['user_id']}'";
execute($sql);
?><div id="error">
<?php echo 'Password Successfully Updated. Back to dashboard';
?></div><?php
return true;
}
} else {
?><div id="error">
<?php echo 'New Password did not match. Press back to try again';
?></div><?php
return false;
}
}
Related
I make a register code email, user, pass and when I click in "zr" insert this info in database, but I'm getting following error:
MySQL error: Column count doesn’t match value count at row 1
Code:
include ('config.php');
include('login_css.php');
$error = "";
if (isset($_POST['zr'])){
$date = date("m d Y");
$user_name = strip_tags($_POST['user']);
$user_pass = strip_tags($_POST['pass']);
$user_email = strip_tags($_POST['email']);
$empty = strip_tags($_POST['none']);
$empty.= strip_tags($_POST['none']);
$empty.= strip_tags($_POST['none']);
$day = strip_tags($_POST['day']);
$month = strip_tags($_POST['month']);
$year = strip_tags($_POST['year']);
$dob = "$day/$month/$year";
if ($user_name == "") {
$error = "Firstname cannot be left empty.";
echo $error;
}
else if ($user_pass == "") {
$error = "Lastname cannot be left empty.";
echo $error;
}
else if ($user_email == "") {
$error = "Email cannot be left empty.";
echo $error;
}
//Check the username doesn't already exist
$check_username = mysql_query("SELECT yser FROM users WHERE username='$user_name'");
$numrows_username = mysql_num_rows($check_username);
if ($numrows_username != 0) {
$error = 'That username has already been registered.';
echo $error;
}
else
{
$check_email = mysql_query("SELECT email FROM users WHERE email='$user_email'");
$numrows_email = mysql_num_rows($check_email);
if ($numrows_email != 0) {
$error = 'That email has already been registered.';
echo $error;
}
else
{
//Register the user
$register = mysql_query("INSERT INTO users(user,pass,email) VALUES('','$user_name','$user_pass','$user_email','$date')") or die(mysql_error());
die('Registered successfully!');
}
}
}
?>
<!-- Form Mixin-->
<!-- Input Mixin-->
<!-- Button Mixin-->
<!-- Pen Title-->
<div class="pen-title">
<title>WebooHub - Join</title>
<h1>WebooHub - Join</h1>
</div>
<!-- Form Module-->
<div class="module form-module">
<div class="toggle"><i class="fa fa-times fa-pencil"></i>
</div>
<div class="form">
<h2>Create Your Account</h2>
<form action="u_register" method="POST">
<button>Join Now</button>
</form>
</div>
<div class="cta">Login?</div>
</div><strong></strong>
The error message is telling you exactly what's wrong. Look at your INSERT statement:
INSERT INTO users(user,pass,email) VALUES('','$user_name','$user_pass','$user_email','$date')
You specify 3 columns, but provide 5 values.
Either provide only the 3 values you want to insert:
INSERT INTO users(user,pass,email) VALUES('$user_name','$user_pass','$user_email')
Or specify the 5 columns for which you're inserting values:
INSERT INTO users(someColumn,user,pass,email,someOtherColumn) VALUES('','$user_name','$user_pass','$user_email','$date')
Also, and this is important, your code is wide open to SQL injection. What this means is that you're blindly executing any code that your users send you in your database queries. Please take a look at this, as well as this. Use query parameters in prepared statements so that you treat user input as values instead of as code.
Additionally, you are storing user passwords in plain text. This is grossly irresponsible password handling. Please hash user passwords correctly. User passwords should be obscured behind a 1-way hash and should never be retrievable, not even by you as the system owner.
Check out columns vs values:
You have 3 columns and 5 values. Those needs to be equal.
$register = mysql_query("INSERT INTO users(user,pass,email) VALUES('','$user_name','$user_pass','$user_email','$date')") or die(mysql_error());
die('Registered successfully!');
Also strongly recommend using mysqli
I've a problem when updating the old password with the new one password_hash, it always said Old password is wrong.
The table: pegawai
Field: nokom, nama, uol1
Here's my code:
<?php session_start();
require "config.php";
$nokom = $_POST['nokom'];
$pswlama = password_hash($_POST['pswlama'], PASSWORD_DEFAULT);
$pswbaru = password_hash($_POST['pswbaru'], PASSWORD_DEFAULT);
$cari = "SELECT * FROM pegawai WHERE nokom ='".$nokom."'";
$result = mysqli_query($conn,$cari);
if (mysqli_num_rows($result) > 0)
{
while ($data = mysqli_fetch_array($result))
{
if(password_verify($pswlama, $data['uol1']))
{
$perintah = "UPDATE pegawai SET uol1 = '$pswbaru' WHERE nokom = '$nokom' ";
if (mysqli_query($conn, $perintah))
{
echo "<script>alert('Success');location.replace('home.php')</script>";
}
else
{
echo "Error updating record: " . mysqli_error($conn);
}
}
else
{
echo "<li>Old password is wrong!</li>";
}
}
}
else
{
echo "Data not found";
}
?>
Any help will be great, thanks.
You are putting a hash in both arguments of password_verify. Read the manual of password_verify and you'll see that the first argument is not supposed to be a hash, but the password itself to compare against the hashed password (argument 2) that is stored in your database.
You are hashing the password before you pass it to password_verify here:
$pswlama = password_hash($_POST['pswlama'], PASSWORD_DEFAULT);
...
if(password_verify($pswlama, $data['uol1']))
You should be passing $_POST['pswlama'] directly to password_verify.
change this
$pswlama = password_hash($_POST['pswlama'], PASSWORD_DEFAULT);
to this. password_verify will handle the rest.
$pswlama = $_POST['pswlama'];
keep the rest of your code the same.
I want to reset user password using php. i got user's current and new password from html form . here's php script to reset password. But it always executes else part even if user enters correct password. how?any solution? i know there might be a simple error but i'm new at this and couldnt find any error.
$uid = $_SESSION['uid'];
$current_pass = $_POST['org_pass'];
$new_pass = $_POST['new_pass'];
if(isset($_POST['submit']))
{
$act_pass = $db_con->prepare("SELECT password FROM user WHERE u_id= ?");
$act_pass->bindParam(1,$uid);
$act_pass->execute();
$actual_pass = $act_pass->fetchColumn();
define('SALT', 'flyingrabbit');
$typed_pass = md5(SALT.$actual_pass);
if ($typed_pass == $current_pass)
{
$new_pass1 = md5(SALT . $new_pass);
$res = $db_con->prepare("UPDATE user SET password= ? WHERE u_id=?");
$res->bindParam(1,$new_pass1);
$res->bindParam(2,$uid);
$res->execute();
header("Location: profile.php");
exit;
}
else
{
echo "<script type=\"text/javascript\">window.alert(\"You entered wrong password.\");window.location.href = 'profile.php';</script>";
}
}
This looks wrong:
$actual_pass = $act_pass->fetchColumn();
// ...
$typed_pass = md5(SALT.$actual_pass);
if ($typed_pass == $current_pass)
You are hashing the information you got from the database which - I assume - is already hashed.
You probably want:
$actual_pass = $act_pass->fetchColumn();
// ...
$typed_pass = md5(SALT.$current_pass);
if ($typed_pass == $actual_pass)
Note that md5 is not recommended to hash passwords.
You should compare hashed $current_pass and **$actual_pas**s.
Replace
$typed_pass = md5(SALT.$actual_pass); with $typed_pass = md5(SALT.$current_pass);
$typed_pass == $current_pass with $typed_pass == $actual_pass
It goes to the else statement because you compare $typed_pass == $current_pass but on the previous line you do this $typed_pass = md5(SALT.$actual_pass) you compare a hashed, salted password to a plain text password
I'm trying to sign users in. I've already made the sign up form, And the database is properly connected.
It keeps on skipping over the first IF statements and going to straight to the "something went wrong error".
Does anybody know why it's not working?
<?php
$pageTitle = "Sign In";
$pageCategory = "Sign In";
$pageCategoryurl = "/signin.php";
//signup.php
include($_SERVER["DOCUMENT_ROOT"] . "/inc/header.php");
include($_SERVER["DOCUMENT_ROOT"] . "/inc/search.php");
?>
<div class="content">
<div id="signinheader"><h2>Sign in</h2></div><div style="clear:both"></div>
<?php
if(isset($_SESSION['signed_in']) && $_SESSION['signed_in'] == true)
{
echo 'You are already signed in, you can sign out if you want.';
}
else
{
if($_SERVER['REQUEST_METHOD'] != 'POST')
{
/*the form hasn't been posted yet, display it
note that the action="" will cause the form to post to the same page it is on */
echo '<form method="post" action="">
<table>
<tr>
<th><label for="username" class="signinlabel">Username:</label></th>
<td><input type="text" name="username" class="signininput"></td>
</tr>
<tr>
<th><label for="userpass" class="signinlabel">Password:</label></th>
<td><input type="password" name="userpass" class="signininput"></td>
</tr>
</table>
<input type="submit" value="Sign In" class="signinbutton">
</form>';
}
else
{
/* so, the form has been posted, we'll process the data in three steps:
1. Check the data
2. Let the user refill the wrong fields (if necessary)
3. Save the data
*/
$errors = array(); /* declare the array for later use */
if(!isset($_POST['username']) OR empty($_POST['username']))
{
$errors[] = 'The username field must not be empty.';
}
if(!isset($_POST['userpass']) OR empty($_POST['userpass']))
{
$errors[] = 'The password field must not be empty.';
}
if(!empty($errors)) /*check for an empty array, if there are errors, they're in this array (note the ! operator)*/
{
echo '<div id="signinerror"><h3>Uh-oh.. a couple of fields are not filled in correctly..</h3>';
echo '<ul>';
foreach($errors as $key => $value) /* walk through the array so all the errors get displayed */
{
echo '<li class="signinerrorli">' . $value . '</li>'; /* this generates a nice error list */
}
echo '</ul></div><div style="clear:both"></div>';
}
else
{
//the form has been posted without, so save it
//notice the use of mysql_real_escape_string, keep everything safe!
//also notice the sha1 function which hashes the password
$username = $_POST['username'];
$userpass = sha1($_POST['userpass']);
$result = mysqli_query($con,"SELECT * FROM users
WHERE username = '$username' AND userpass = '$userpass");
if(!$result)
{
//something went wrong, display the error
echo 'Something went wrong while signing in. Please try again later.';
//echo mysqli_error(); //debugging purposes, uncomment when needed
}
else
{
//the query was successfully executed, there are 2 possibilities
//1. the query returned data, the user can be signed in
//2. the query returned an empty result set, the credentials were wrong
if(mysqli_num_rows($result) == 0)
{
echo 'You have supplied a wrong user/password combination. Please try again.';
}
else
{
$_SESSION['signed_in'] = true;
//we also put the user_id and user_name values in the $_SESSION, so we can use it at various pages
while($row = mysqli_fetch_assoc($result))
{
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
$_SESSION['useremail'] = $row['useremail'];
}
echo 'Welcome, ' . $_SESSION['username'] . '. Proceed to the homepage.';
}
}
}
}
}
?>
</div>
<?php
include($_SERVER["DOCUMENT_ROOT"] . "/inc/footer.php");
?>
Your error is on your query:
$result = mysqli_query($con,"SELECT * FROM users
WHERE username = '$username' AND userpass = '$userpass");
You miss a quote at the end.
$result = mysqli_query($con,"SELECT * FROM users
WHERE username = '$username' AND userpass = '$userpass' ");
^here
Your query to the database is resulting in some sort of database failure, as !$result, as you have it, will only resolve to true when $result is false. In your case, $result would only be false if something went wrong with the query.
The answer? You have a syntax error:
You have this:
$result = mysqli_query($con,"SELECT * FROM users
WHERE username = '$username' AND userpass = '$userpass");
Where it should be this
$result = mysqli_query($con,"SELECT * FROM users
WHERE username = '$username' AND userpass = '$userpass'");
Do you see it? You were missing that last ' :)
I like to call these "missing semicolon" errors, because they're impossible to find, drive you crazy, and are so simple to fix that it makes you feel dumb.
I am new in PHP and need help with my below code. When I am entering wrong userid instead of giving the message "userid does not exist" it is showing "password/id mismatch. Please guide me where I am wrong.
<?php
session_start();
$id = $_POST['userid'];
$pwd = $_POST['paswd'];
$con = mysqli_connect("localhost", "????", "????", "??????");
if ($con) {
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
if ($result) {
$row = mysql_fetch_array($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist !!!";
}
} else {
echo "Connection failed - ".mysqli_error()." -- ".mysqli_errno();
}
?>
The main problem you have is that you're mixing up between the mysqli and mysql functions. These two libraries are not compatible with each other; you must only use one or the other.
In other words, the following line is wrong:
$row=mysql_fetch_array($result);
It needs to be changed to use mysqli_.
While I'm here, going off-topic for a moment I would also point out a few other mistakes you're making:
You aren't escaping your SQL input. It would be extremely easy to hack your code simply by posting a malicious value to $_POST['userid']. You must use proper escaping or parameter binding. (since you're using mysqli, I recommend the latter; it's a better technique).
Your password checking is poor -- you don't appear to be doing any kind of hashing, so I guess your passwords are stored as plain text in the database. If this is the case, then your database is extremely vulnerable. You should always hash your passwords, and never store the actual password value in the database.
I've gone off topic, so I won't go any further into explaining those points; if you need help with either of these points I suggest asking separate questions (or searching here; I'm sure there's plenty of existing advice available too).
else
{
echo "ID/Password Mismatch";
}
is connected with the
if($row["userid"]==$id && $row["paswd"]==$pwd)
{
So since you are giving a wrong id. It echo's: ID/Password Mismatch
Also the else at if ($result) { wont ever show since
$result = mysqli_query($con, "SELECT * FROM users WHERE userid=$id");
You need some additionnal checks:
select * return 1 row (not 0, and not more)
you need to protect the datas entered by the html form (for example someone could enter 1 or 1 to return all rows
<?php
session_start();
$con = mysqli_connect("localhost", "????", "????", "??????");
$id = mysqli_real_escape_string($_POST['userid']);
$pwd = mysqli_real_escape_string($_POST['paswd']);
if ($con) {
// don't even do the query if data are incomplete
if (empty($id) || empty($pwd)
$result = false;
else
{
// optionnal : if userid is supposed to be a number
// $id = (int)$id;
$result = mysqli_query($con, "SELECT * FROM users WHERE userid='$id'");
}
if (mysqli_num_rows($result) != 1)
$result = false;
if ($result) {
$row = mysqli_fetch_assoc($result);
if ($row["userid"] == $id && $row["paswd"] == $pwd) {
echo "Welcome! You are a authenticate user";
if ($id == $pwd)
//my default login id and password are same
{
header("Location: changepwd.html");
} else {
header("Location: dataentry.html");
}
} else {
echo "ID/Password Mismatch";
}
} else {
echo "User does not Exist, or incomplete input";
}
} else {
echo "Connection failed - " . mysqli_error() . " -- " . mysqli_errno();
}
?>
Try with isset() method while you are checking if $result empty or not.
that is in line
if ($result) {.......}
use
if (isset($result)) { .......}
$result is always true, because mysqli_query() only returns false if query failed.
You could check if $result has actual content with empty() for example.
You can use this sql compare password as well with userid
$sql= "SELECT * FROM users WHERE userid='".$id.", and password='".$pwd."'";