formatted code:
<?php
require_once 'connectvars.php';
if (isset($_POST['submit'])) {
//set vars
$oldpw = mysqli_real_escape_string($dbc, trim($_POST['oldpw']));
$newpw = mysqli_real_escape_string($dbc, trim($_POST['newpw']));
$retype = mysqli_real_escape_string($dbc, trim($_POST['retype']));
$query = mysqli_query($dbc, 'SELECT password from user_info WHERE password = "hash(\'SHA256\',$oldpw)" and user_id = "$SESSION[\'user_id\']"'); // this line is "not working well"
if (strlen($newpw) < 7) {
if (strlen($newpw) > 32 ) {
if (mysqli_num_row($query) == 1) {
if ($newpw == $retype) {
mysqli_query($dbc, "UPDATE user_info SET password = 'hash('SHA256',$newpw)'");
$msg = "You successfully changed your password";
}
else {
$msg = "Your old password doesn't match.";
}
}
else {
$msg = "You must enter your old password correct.";
}
}
else {
$msg = "Your password must contain 32 characters or less.";
}
}
else {
$msg = "Your new password must contain at least 7 characters.";
}
?>
I think you want to improve your sql syntax.
'SELECT password
from user_info
WHERE password = "hash(\'SHA256\',$oldpw)"
and user_id = "$SESSION[\'user_id\']"'
may be corrected to
"SELECT password
from user_info
WHERE password = '" . hash('SHA256',$oldpw) ."'
and user_id = '" . $_SESSION['user_id'] . "'"
to propperly escape the string. Try to correct your update statement the same way.
Related
I am confused about how to encrypt the new password to go in the database. When I enter the password it will encrypt and check the database correct and to verify for the new password it will just change it to plain text.
if (count($_POST) > 0) {
$result = mysqli_query($conn, "SELECT *from users WHERE id='" . $_SESSION["id"] . "'");
$row = mysqli_fetch_array($result);
if (MD5(mysqli_real_escape_string($_POST["currentPassword"] == $row["password"]))) {
mysqli_query($conn, "UPDATE users set password='" . $_POST["newPassword"] . "' WHERE id='" . $_SESSION["id"] . "'");
$message = "Password Changed";
} else
$message = "Current Password is not correct";
}
// password encryption for security.
$salt = mcrypt_create_iv(22, MCRYPT_DEV_URANDOM);
$salt = base64_encode($salt);
$salt = str_replace('+', '.', $salt);
$hash = crypt($pass, '$2y$10$'.$salt.'$');
//echo ("".$hash."<br />\n");
$pass is the password from the password input
save $hash to the database
verify the password with that got from the database $hash
if(password_verify($pass, $hash)) {
echo 'Password is valid!';
} else {
echo 'Invalid password.';
}
update and try that procedure
for simple application you can use base64_encode() to encrypt and store it into database when new password is entered. and for login also encrypt the entered password and match it with database.
your code:
if (count($_POST) > 0)
{
$result = mysqli_query($conn, "SELECT *from users WHERE id='" . $_SESSION["id"] . "'");
$row = mysqli_fetch_array($result);
$entered_password = base64_encode($_POST["currentPassword"]);
$new_password = base64_encode($_POST["newPassword"]);
$id = $_SESSION["id"] ;
if ($entered_password == $row["password"]))) {
$result = mysqli_query($conn, "UPDATE users set password='" . $new_password . "' WHERE id='" .$id. "'");
$message = "Password Changed";
} else
$message = "Current Password is not correct";
}
its a simply way.
//password encryption
$user_password = "1234";
$hash_pass = password_encryption($user_password, PASSWORD_BCRYPT, array('cost'=>10);
//"$user_password"-password obtained from the user input
//"$hash_pass" -encrypted password stored in a database
//verify the user password with that obtained from the database
if(password_verify($user_password, $hash_pass)){
echo "password is valid";
}else{
echo "password is not valid";
}
try this out.
This is my code, i want to update the password with the given new password $new_password, validate it with $new_password2 and check if the current given password matches the $old_password.
<?php
if (isset($_POST['submit'])) {
//validations
$required_fields = array("username", "old_password", "password", "password2");
validate_presences($required_fields);
$fields_with_max_lengths = array("username" => 30);
validate_max_lengths($fields_with_max_lengths);
if(empty($errors)) {
//process the form
$id = $admin["id"];
$username = mysql_prep($_POST["username"]);
$new_password = password_encrypt($_POST["password"]);
$old_password = password_encrypt($_POST["old_password"]);
$new_password2 = password_encrypt($_POST["password2"]);
The two passwords you must give must be equal to each other to change the password. All three passwords are hashed. $new_password and $new_password2 are needed to validate the new password. The $old_password must also be updated with the $new_password. It must be changed if the id equals the one in the database and if the $old_password matches the current $old_password.
if ($new_password == $new_password2) {
//update
$query = "UPDATE admins SET ";
$query .= "username = '{$username}', ";
$query .= "password = '{$new_password}', ";
$query .= "old_password = '{$new_password}', ";
$query .= "password2 = '{$new_password}' ";
$query .= "WHERE id = {$id} ";
$query .= "AND old_password = '{$old_password}' ";
$query .= "LIMIT 1";
$result = mysqli_query($connection, $query);
if ($result && mysqli_affected_rows($connection) == 1) {
//success
$_SESSION["message"] = "Admin updated.";
redirect_to("manage_admins.php");
} else {
//failure
$_SESSION["message"] = "Admin update failed1";
}
} else {
$_SESSION["message"] = "Admin update failed2";
}
} else {
$_SESSION["message"] = "Admin update failed3";
}
} else {
}
?>
You may have meant password_hash instead of password_encrypt. Still, this would be the wrong usage. Look into password_verify. The basic idea is that you get the current hashed password for that user from the DB and then use password_verify to check the user entry against the stored hash.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
so i tried to convert a little bit of MYSQL to the new PDO;
$u_check = mysql_query("SELECT username FROM users WHERE username='un'");
$check = mysql_num_rows($u_check);
if($check == 0){
echo "Do this";
}
How i did it in PDO:
$u_check = $databaseConnection->prepare("SELECT username FROM users WHERE :username = '$un'");
$check = $databaseConnection->query($u_check);
if($check == 0){
echo "do stuff"
}
But as expeced i get an error:
Warning: PDO::query() expects parameter 1 to be string, object given
in F:\xampp\htdocs\SocialMedia\first\index.php on line 27
Line 27: $check = $databaseConnection->query($u_check);
I have no idea how to get the same result in PDO
Thanks in advance for the help!
EDIT 1:
I have this now:
if($reg) {
if($em==$em2){
$u_check = $databaseConnection->prepare("SELECT username FROM users WHERE :username = '$un'");
$u_check->bind_param("s", "un");
$result = $u_check->execute();
if($result){
echo "hoi";
}
}
}
gives me:
Fatal error: Call to undefined method PDOStatement::bind_param() in
F:\xampp\htdocs\SocialMedia\first\index.php on line 26
EDIT 2: my code at the moment;
<?php include("inc/header.inc.php");?>
<?php
$reg = $_POST['reg'];
$fn = "";
$ln = "";
$un = "";
$em = "";
$em2 = "";
$pswd = "";
$pswd2 = "";
$d = "";
$fn = strip_tags($_POST['fname']);
$ln = strip_tags($_POST['lname']);
$un = strip_tags($_POST['uname']);
$em = strip_tags($_POST['email']);
$em2 = strip_tags($_POST['email2']);
$pswd = strip_tags($_POST['password']);
$pswd2 = strip_tags($_POST['password2']);
$d = date("d-m-Y");
if($reg) {
if($em==$em2){
$u_check = $databaseConnection->prepare("SELECT username FROM users WHERE username= :username");
$u_check->bindParam(':username', $un);//un is the given username that user types
$u_check->execute();
$check = $u_check->rowCount();
if($check > 0){
if($fn&&$ln&&$un&&$em&&$em2&&$pswd&&$pswd2){
if($pswd==$pswd2){
if(strlen($un)>25||strlen($fn)>25||strlen($ln)>25){
echo "Maximum characters is 25!";
}else{
if(strlen($pswd)>30||strlen($pswd)<5){
echo "Your pass must be between 5 and 30 characters!";
}else{
$pswd = md5($pswd);
$pswd2 = md5($pswd2);
$query = $databaseConnection->prepare("INSERT INTO users (username, first_name, last_name, email, password, sign_up_date, activated) VALUES (:un, :fn, :ln, :em, :pswd, :d, '0')");
$query->execute();
die("<h2>Welcome to Profiles</h2>Login to your account to get started...");
}
}
}
}
}else{
echo "Already exists!";
}
}
}
?>
So, now i get the message "Already exists!" everytime,
Altho the setup itself does not work, its not putting the stuff from the form in ....
EDIT 3
I get this:
Parse error: syntax error, unexpected '}' in
F:\xampp\htdocs\SocialMedia\first\index.php on line 50 which is line
if($pswd!=$pswd2){
$errors[] .= 'Passwords are not the same';
}elseif(strlen($pswd)>30||strlen($pswd)<5){
$errors[] .='Your pass must be between 5 and 30 characters!'
}else{
$pswd_md = md5($pswd);
}
which is this line:
}else{
Your code is wrong...Try this one:
<?php include("inc/header.inc.php"); ?>
<?php
function display_errors($errors){
$display = '<ul>';
foreach ($errors as $error){
$display .= '<li>'.$error.'</li>';
}
$display .= '</ul>';
return $display;
}
$reg = $_POST['reg'];
$fn = "";
$ln = "";
$un = "";
$em = "";
$em2 = "";
$pswd = "";
$pswd2 = "";
$d = "";
if(isset($reg)) {
$errors = array();
$fn = strip_tags($_POST['fname']);
$ln = strip_tags($_POST['lname']);
$un = strip_tags($_POST['uname']);
$em = strip_tags($_POST['email']);
$em2 = strip_tags($_POST['email2']);
$pswd = strip_tags($_POST['password']);
$pswd2 = strip_tags($_POST['password2']);
$d = date("d-m-Y");
$required = array('fname','lname','uname','email','email2','password','password2');
foreach($required as $field){
if($_POST[$field] == ''){
$errors[] .= $field. ' is required';
}
}
if(strlen($un)>25||strlen($fn)>25||strlen($ln)>25){
$errors[] .= "Maximum characters is 25!";
}
if($pswd!=$pswd2){
$errors[] .= 'Passwords are not the same';
}elseif(strlen($pswd)>30||strlen($pswd)<5){
$errors[] .='Your pass must be between 5 and 30 characters!'
}else{
$pswd_md = md5($pswd);
}
if($em != $em2){
$errors[] .= 'Emails are not the same';
}
$u_check = $databaseConnection->prepare("SELECT username FROM users WHERE username= :username");
$u_check->bindParam(':username', $un);//un is the given username that user types
$u_check->execute();
$check = $u_check->rowCount();
if($check > 0){
$errors[] .= 'User Exists. Choose another username';
}
if(!empty($errors)){
echo display_errors($errors);
}else{
$ac = 0;
$query = $databaseConnection->prepare("INSERT INTO users (username, first_name, last_name, email, password, sign_up_date, activated) VALUES (:un, :fn, :ln, :em, :pswd, :d, :ac)");
$query->bindParam(':un',$un);
$query->bindParam(':fn',$fn);
$query->bindParam(':ln',$ln);
$query->bindParam(':em',$em);
$query->bindParam(':pswd',$pswd_md);
$query->bindParam(':d',$d);
$query->bindParam(':ac',$ac);
$query->execute();
}
if($query){
//INSERT SUCCESS
echo 'Success';
}else{
echo 'Failed;'
}
}
?>
It is because for query() you need a String, but you give an object (Look: http://php.net/manual/de/pdo.query.php)
There is an example:
<?php
function getFruit($conn) {
$sql = 'SELECT name, color, calories FROM fruit ORDER BY name';
foreach ($conn->query($sql) as $row) {
print $row['name'] . "\t";
print $row['color'] . "\t";
print $row['calories'] . "\n";
}
}
?>
If you want to use prepare have a look at: http://php.net/manual/de/pdo.prepare.php
You have to use $var->execute(array($var1, $var2));
If I see correctly you want to check if the given username exists in the database. Call ->execute() on the prepared statement and use rowCount() on the returned object to get the number of results.
Check the documentation for more info: PDO rowCount and PDO Prepare
But if you really only need the number of rows where the username is the given username (since you select username and use it in the condition also) you can simply select the number:
SELECT count(username) FROM users GROUP BY username HAVING username = $username
I am currently programming php, and enjoying it.
I know how to code a script that will update a user's email address or password in different processes. I need to update them in one form. Here's a screenshot:
I need to update one of them, if he didn't enter a password then update the email, if he didn't enter the email update the password, if he entered both update both..
the script I am currently coding has been twirling around my mind and I have lost myself over and over and over...
update_settings_process.php: (I have Updated the script!!)
<?php
error_reporting(1);
session_start();
include("../common/config.php");
include("../common/conn.php");
$case = '';
$error_str = '';
//email:
$email = stripslashes($_REQUEST['email_address']);
//password:
$old_password = trim($_REQUEST['old_password']);
$password = trim($_REQUEST['password']);
$conf_password = trim($_REQUEST['conf_password']);
$get_users_qry = "Select password From users where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."' AND password = '".md5($old_password)."' AND status = 1";
$get_users = $db->get_row($get_users_qry,ARRAY_A);
$qry = "Select email from users where email = '$email' and username != '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'";
$res = mysql_query($qry);
echo 'Email:' . $email;
echo '<p>';
echo 'Old Password: '. $old_password;
echo '<p>';
echo 'Password:' . $password;
echo '<p>';
echo 'Confrim Password:' . $conf_password;
echo '<p>';
if(filter_var($email, FILTER_VALIDATE_EMAIL) && (strlen($password) > 5) && $get_users && !mysql_num_rows($res))
{
//update email and password
$update_password = mysql_query("UPDATE users
SET
password='".md5($password)."' where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'");
$update_email = mysql_query("UPDATE users
SET
email='".$email."' where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'");
echo 'Email and Password Has been Updated!';
die();
}
if ($email == '' && (strlen($password) == 0))
{
$error_str .= "There is nothing to update";
echo $error_str;
die();
}
if ($email == '' && (strlen($password) == 0))
{
$error_str .= "Use a secure Password";
echo $error_str;
$case = 0;
die();
}
else
{
if($email == '' && (strlen($password) < 5))
{
$error_str .= "Password must be atleast 5 characters";
echo $error_str;
$case = 0;
die();
}
else
{
if ($email == '' && $password != $conf_password)
{
$error_str .= "Passwords Do not Match";
echo $error_str;
$case = 0;
die();
}
else
{
if($email == '' && !$get_users)
{
$error_str .= "Please enter correct old password <br>";
echo $error_str;
$case = 0;
die();
}
else
{
//update password only!
if(strlen($password) == 0)
{
die();
}
else
{
$update_password = mysql_query("UPDATE users
SET
password='".md5($password)."' where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'");
echo "done-SEPARATOR-Password changed successfully";
exit();
}
}
}
}
}
if(strlen($password) == 0)
{
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
$error_str .="Invalid Email <br>";
echo $error_str;
$case = 0;
die();
}
else
{
$qry = "Select email from tbl_admin where email = '$email' and username != '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'";
$res = mysql_query($qry);
if(mysql_num_rows($res))
{
$error_str = "$email already exist<br>";
$case = 0;
}
else
{
//update email only!
$update_email = mysql_query("UPDATE users
SET
email='".$email."' where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'");
echo "done-SEPARATOR-Email address changed successfully";
die();
}
}
}
if($case = 0)
{
echo $error_str;
die();
}
?>
I have really lost myself in there, and I couldn't figure out why because of that..
I have updated the script:
it can update password and email at the same time
it can update password only
it can not update email only.. <-- im stuck here
here's the update email only part:
if(strlen($password) == 0)
{
if (!eregi("^[_a-z0-9-]+(\.[_a-z0-9-]+)*#[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,3})$", $email)){
$error_str .="Invalid Email <br>";
echo $error_str;
$case = 0;
die();
}
else
{
$qry = "Select email from tbl_admin where email = '$email' and username != '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'";
$res = mysql_query($qry);
if(mysql_num_rows($res))
{
$error_str = "$email already exist<br>";
$case = 0;
}
else
{
//update email only!
$update_email = mysql_query("UPDATE users
SET
email='".$email."' where username = '".$_SESSION['LOGIN_BALANCE_FRONT']['name']."'");
echo "done-SEPARATOR-Email address changed successfully";
die();
}
}
}
There are some mistakes in your if-clauses. Try changing them to something like this:
$email == ''
1) = is the assignment operator, == is the comparison operator, which you weirdly used correctly with the strlen($password) comparison. The mnemonic is "Twice is for T(w)sets, Once is for Owssignment" (works best in a North English accent).
2) You're doing something rather odd with the strlen() function. strlen() always returns an integer (until someone invents half-letters). Consequently, strlen == '' is a bad, bad test. What you would want that line to look like is this:
if ($email = '' && (strlen($password) == 0))
(though why you didn't use strlen() both times puzzles me!)
3) Do not, not even jokingly, use the word 'retard' in code, or at least be bright enough not to post it publicly. It's ableist and, frankly, stupid. There are loads of people on this board who are extremely experienced and would, were they not better (wo)men, think you to be one for using a single = to test. Never call your users, or indeed anyone, a 'retard'. It's not funny.
I am trying to input a check-box for terms and conditions in a form, but when I registered the form without ticking the box the registration went through , (which was not suppose to be). Please help have a look.
<?php
echo "<h2>Register</h2>";
$submit = $_POST['register'];
//form data
$fullname = mysql_real_escape_string(htmlentities(strip_tags($_POST['fullname'])));
$username = strtolower(mysql_real_escape_string(htmlentities(strip_tags($_POST['username']))));
$password = mysql_real_escape_string(htmlentities(strip_tags($_POST['password'])));
$repeatpassword = mysql_real_escape_string(htmlentities(strip_tags($_POST['repeatpassword'])));
$email = mysql_real_escape_string(htmlentities(strip_tags($_POST['email'])));
$houseno = mysql_real_escape_string(htmlentities(strip_tags($_POST['houseno'])));
$addressa = mysql_real_escape_string(htmlentities(strip_tags($_POST['addressa'])));
$addressb = mysql_real_escape_string(htmlentities(strip_tags($_POST['addressb'])));
$addressc = mysql_real_escape_string(htmlentities(strip_tags($_POST['addressc'])));
$county = mysql_real_escape_string(htmlentities(strip_tags($_POST['county'])));
$state = mysql_real_escape_string(htmlentities(strip_tags($_POST['state'])));
$country = mysql_real_escape_string(htmlentities(strip_tags($_POST['country'])));
$accept = mysql_real_escape_string(htmlentities(strip_tags($_POST['accept'])));
if ($submit)
{
$namecheck = mysql_query("SELECT username FROM reusers WHERE username='$username'");
$count = mysql_num_rows($namecheck);
if($count!=0)
{
die("Username already taken!");
}
//check for registration form details
if ($fullname&&$username&&$password&&$repeatpassword&&$email&&$houseno&&$addressa&&$county&&$state&&$country)
{
if($accept!= 1)
{
if ($password==$repeatpassword)
{
//check char lenght of username and fullname
if (strlen($username)>25||strlen($fullname)>25)
{
echo "Lenght of username or fullname is too long";
}
else
{
//check password length
if(strlen($password)>25||strlen($password)<6)
{
echo"Password must be between 6 and 25 characters";
}
else
{
//check password length
$emailcheck = mysql_query("SELECT email FROM reusers WHERE email='$email'");
$ecount = mysql_num_rows($emailcheck);
if($ecount!=0)
{
echo"email already registered Please sign in into your account to continue";
}
else
{
//generate random code
$code = rand(11111111,99999999);
//send activation email
$to = $email;
$subject = "Activate your account";
$headers = "From: donotreply#reacheasy.co.uk";
$body = " Hello $fullname,\n\nUsername $username,\n\n Password $password ,\n\nYou registered `and need to activate your account. Click the link below or paste it into the URL bar of your browser\n\nhttp://reach.co.uk/activate.php?code=$code\n\nThanks!";
if (!mail($to,$subject,$body,$headers))
echo "We couldn't sign you up at this time. Please try again later.";
else
{
//register the user!
//encript password
$password = md5($password);
$repeatpassword = md5($repeatpassword);
$queryreg = mysql_query("
INSERT INTO reusers VALUES ('','$fullname','$username','$password','$email','$code','0','houseno','addressa','addressb','addressc','county','state','country')
");
die("You have been registered successfully! Please check your email ($email) to activate your account<a href='index.php'>Return to login page</a>");
}
}
}
}
}
else
echo"Your passwords do not match!";
}
else
echo"Please read and accept Terms and Conditions before registering!";
}
else
echo "Please fill in <b>all</> fields!";
}
?>
$accept = ($_POST['accept'] ? 1:0);
You must use
if($accept == 1)
because $_POST['accept'] = 1 when you check the checkbox.
Now return Please read and accept Terms and Conditions before registering! when checkbox is checked and register the user when checkbox is not checked.