I have my php page, in which i have 3 fields old pass, new pass, confirm new pass. I'm trying to chnge the password of my id from which i am logged in. The program first check in the database and change the password of the logged in user. I have tried a code for it. But whenever i fill all the fields and click DONE. It just refreshes the page and nothing happens, no changing in the database and no message is displayed on the page. Can some one find out the problem?

Thanks in ADVANCE.

<?php session_start();
?>
<?php include_once("../includes/connection.php"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Example form</title>
<style type="text/css">
.container1 {
    width: 500px;
    clear: both;
}
.container1 input {
    width: 100%;
    clear: both;
}

</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Change Password</title>
</head>
<body>


<div id="container">
    <div id="header">
        <h1 style="text-align:left">Quality Management<span class="off"> Cell</span></h1>

    </div>   

    <div id="menu">
        <ul>
            <li class="menuitem"><a href="cms.php">Home</a></li>
            <li class="menuitem"><a href="cms-attendance.php">Attendance</a></li>
            <li class="menuitem"><a href="cms-courses.php">Courses</a></li>
            <li class="menuitem"><a href="cms-settings.php">Settings</a></li>

        </ul>
        <a style="text-align:right" href="cms-logout.php">Logout</a>
    </div>

    </div>        
    <div id="content" align="justify">
    <div id="content_top"></div>
    <div id="content_main">
<div id="wrapper">             

<form class="login-form" method ="post" action="">
      <label for="password">Old Password:</label>
      <input name="old_password"/><br /><br />

      <label for="password">New Password:</label>
      <input name="n_password"/><br /><br />

      <label for="password">Confirm new Password:</label>
      <input name="new_password"/><br />
        <p>

        <br />
        <input class="button" name="submit" type="Submit" value="Done"/>

  </form>
<?php
if(isset($_POST['old_password']) && isset($_POST['password']) && isset($_POST['new_password'])){
    $old_pass = $_POST['old_password'];
    $password = $_POST['n_password'];
    $new_pass = $_POST['new_password'];

if (isset($_SESSION['user_name'])){
$username = $_SESSION['user_name'];

$query_pass = "SELECT user_pass FROM users WHERE user_name = '".$_SESSION['user_name']."'";
$result_set = mysql_query($query_pass) or die(mysql_error());
$pass_rows = mysql_affected_rows($result_set) or die (mysql_error());

$pass_set  = mysql_fetch_array($pass_rows);
while ($pass_set = mysql_fetch_array($result_set)){
        $pass_set['user_id'];
        $pass_set['user_name'];
        $pass_set['user_pass'];

if(empty($old_pass)|| empty($password)|| empty($new_pass)){
echo "ALL THE FIELDS ARE REQUIRED"; 
}
else if ($pass_set['user_pass']!=$old_pass){
echo "PASSWORD DID'NT MATCH!";  
}
else if ($password != $new_pass){
echo "NEW PASS DID'NT MATCH!";
}
else if ($new_pass == $old_pass){
echo "CAN NOT MATCH THE OLD PASSWORD";
}
else {

$change_pass = "UPDATE users SET user_pass = '".$new_pass."' WHERE user_name = '".$_SESSION['user_name']."'";
$pass_query = mysql_query($change_pass) or die (mysql_error());
if ($pass_query){
echo "Password Changed";
}
else {
echo "Invalid"; 
}
}
}}
}
?>                

        <p>&nbsp;</p>
        <p>&nbsp;</p>

    <div id="content_bottom"></div>

  </div>
</div>
</body>
</html>

try removing ". sign on line 97 like this and retry

$change_pass = "UPDATE users SET user_pass = '$new_pass' WHERE user_name = '$_SESSION[user_name]'";

dear, there is no change:(

Can you post the connection.php? also change $_POST['password'] to $_POST['n_password'] as password is not define

from

if(isset($_POST['old_password']) && isset($_POST['password']) && isset($_POST['new_password']))

to

if(isset($_POST['old_password']) && isset($_POST['n_password']) && isset($_POST['new_password']))

"Warning: mysql_affected_rows(): supplied resource is not a valid MySQL-Link resource in C:\xampp\htdocs\fyp\cms\cms-settings.php on line 78"

After applying your changes, i am having this.

Member Avatar for diafol

A few issues:

You haven't hashed your passwords they need to be salted and then hashed.
You are using deprecated mysql_* functions, you need to use mysqli_* or PDO.
You are inserting unsanitized input variables to the SQL, leaving you exposed to SQL injection.

You should attempt to sort out these issues.

maybe its ur update query:

$change_pass = "UPDATE users SET user_pass = '".$new_pass."' WHERE user_name = '".$_SESSION['user_name']."'";

change '".$new_pass."' to '$new_pass'

so its:

$change_pass = "UPDATE users SET user_pass = '$new_pass' WHERE user_name = '".$_SESSION['user_name']."'";
Member Avatar for diafol

Here's a quick version, which may be of help. Feel free to take it apart, use it or completely ignore it. It relies on PHP 5.5 though.

handler.php
<?php
// You must have PHP 5.5 installed as it makes use of the new password_hash() and 
// password_verify(). 
// This also uses PDO, but can be easily adapted to mysqli 
// The regex pattern is very simple and may need to be edited to taste
// Likewise the size of passwords allowed may be edited by changing $minLength and 
// $maxLength accordingly. The range is inclusive.
// The $encoding is included as mb_strlen() is used - this is not required if you
// wish to change the function mb_strlen to just str_len.


session_start();

/*
//TESTING
$_SESSION['user_id'] = 1;
if(!isset($_SESSION['user_id'])){ echo "no session user_id";exit;}
*/

if(!isset($_SESSION['user_id'])) header("Location: index.php");


//INITIALIZE VARIABLES
$user_id = $_SESSION['user_id'];

$errors = array();
$success = '';

$minLength = 6;
$maxLength = 20;

$encoding = 'UTF-8';

$pwPattern = '/^\w+$/';
$patternCharacters = "lowercase or uppercase unaccented Latin letters (a-Z), numbers (0-9) or underscores ( _ )";

define("ALGO", PASSWORD_BCRYPT); 

if(isset($_SESSION['changePW'])) unset($_SESSION['changePW']);

$dsn = 'mysql:dbname=##########;host=localhost';
$user = '##########';
$password = '############';

$select = "SELECT pw FROM users WHERE user_id = :user_id LIMIT 1";
$update = "UPDATE users SET pw = :hashed WHERE user_id = :user_id";



//OK test for form submission (or cURL or Ajax) 
if(isset($_POST['pw']) && isset($_POST['new_pw']) && isset($_POST['confirm_pw']))
{
    //Grab form data
    $pw = trim($_POST['pw']);
    $new_pw = trim($_POST['new_pw']);
    $confirm_pw = trim($_POST['confirm_pw']);
    //Check fields have data in them / not empty
    if(!$pw || !$new_pw || !$confirm_pw)
    {
        $errors[] = "Password fields cannot be empty or just contain whitespace characters";
    }
    //Can use strlen() if you don't allow multibyte characters - which this example doesn't
    if(mb_strlen($pw, $encoding) < $minLength || mb_strlen($new_pw, $encoding) < $minLength || mb_strlen($confirm_pw, $encoding) < $minLength) 
    {
        $errors[] = "Password fields must contain at least $minLength characters";
    }
    //Check new passwords match
    if($new_pw !== $confirm_pw) 
    {
        $errors[] = "The new password fields do not match";
    }
    //Ensure new passwords only contain characters allowed by the regex pattern
    if(!preg_match($pwPattern,$pw) || !preg_match($pwPattern,$new_pw) || !preg_match($pwPattern,$confirm_pw)) 
    {
        $errors[] = "Passwords can only contain $patternCharacters";
    }
    //Only proceed to process if no errors thus far
    if(empty($errors))
    {
        //Connect via PDO
        try {
            $dbh = new PDO($dsn, $user, $password);
        } catch (PDOException $e) {
            $errors[] = 'Connection failed: ' . $e->getMessage();
        }
        //If OK, proceed
        if(empty($errors))
        {
            $statement = "SELECT pw FROM users WHERE user_id = :user_id LIMIT 1";
            $stmt = $dbh->prepare($select);
            $stmt->execute(array(':user_id'=>$user_id));
            //If user with $user_id exists
            if($stmt->rowCount())
            {
                $result = $stmt->fetchColumn();
                //Check current hashed password against $pw from form
                if(!password_verify($pw, $result))
                {   
                    $errors[] = "You have provided the wrong password"; 
                }else{
                    //Hash the new password and update the users table
                    $hashed = password_hash($new_pw, ALGO);         
                    $stmt = $dbh->prepare($update);
                    $stmt->execute(array(':hashed'=>$hashed, ':user_id'=>$user_id));
                    if($stmt->rowCount())
                    {
                        $success = "Your password was changed"; 
                    }

                }
            //User with $user_id not in DB table! Odd.  
            }else{
                $errors[] = 'Your details could not be retrieved from the database';    
            }
        }
    }
}else{
    $errors[] = 'You tried to update data without submitting the form'; 
}

$_SESSION['changePW'] = array('success'=>$success,'errors'=>$errors);

/*
//TESTING
echo "<pre>";
print_r($_SESSION['changePW']);
echo "</pre>";
*/

header("Location: formpage.php");   
exit;
?>
formpage.php
<?php
session_start();
$msg='';
if(isset($_SESSION['changePW']))
{
    $errors = $_SESSION['changePW']['errors'];  
    $success = $_SESSION['changePW']['success'];
    unset($_SESSION['changePW']);
    if($success)
    {
        $msg = '<ul><li class="success">' . $success . '</li></ul>';    
    }else{
        $msg = '<ul><li class="error">' . implode('</li><li>', $errors) . '</li></ul>';
    }
}

?>

<!DOCTYPE HTML>
<html>
<head>
<meta charset="utf-8">
<title>User Profile</title>
</head>

<body>
<form method="post" action="handler.php" >
    <label for="pw">Current Password</label>
    <input type="password" name="pw" id="pw" />
    <label for="pw">New Password</label>
    <input type="text" name="new_pw" />
    <label for="pw">Confirm New Password</label>
    <input type="text" name="confirm_pw" />
    <input type="submit" name="submit" value="Change Password" />
</form>
<div><?php echo $msg;?></div>
</body>
</html>

I have done the following changes to my code for salting and hashing , is that fine ? diafol?

<?php session_start();
?>
<?php include_once("../includes/connection.php"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Example form</title>
<style type="text/css">
.container1 {
    width: 500px;
    clear: both;
}
.container1 input {
    width: 100%;
    clear: both;
}

</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Change Password</title>
</head>
<body>


<div id="container">
    <div id="header">
        <h1 style="text-align:left">Quality Management<span class="off"> Cell</span></h1>

    </div>   

    <div id="menu">
        <ul>
            <li class="menuitem"><a href="cms.php">Home</a></li>
            <li class="menuitem"><a href="cms-attendance.php">Attendance</a></li>
            <li class="menuitem"><a href="cms-courses.php">Courses</a></li>
            <li class="menuitem"><a href="cms-settings.php">Settings</a></li>

        </ul>
        <a style="text-align:right" href="cms-logout.php">Logout</a>
    </div>

    </div>        
    <div id="content" align="justify">
    <div id="content_top"></div>
    <div id="content_main">
<div id="wrapper">             

<?php
$current_page = $_SERVER['PHP_SELF'];
?>
<form class="login-form" method ="post" action="<?php echo $current_page; ?>">
      <label for="password">Old Password:</label>
      <input name="old_password"/><br /><br />

      <label for="password">New Password:</label>
      <input name="n_password"/><br /><br />

      <label for="password">Confirm new Password:</label>
      <input name="new_password"/><br />
        <p>

        <br />
        <input class="button" name="submit" type="Submit" value="Done"/>

  </form>
<?php
if(isset($_POST['old_password']) && isset($_POST['n_password']) && isset($_POST['new_password'])){
    $old_pass = mysql_real_escape_string($_POST['old_password']);
    $password = mysql_real_escape_string($_POST['n_password']);
    $new_pass = mysql_real_escape_string($_POST['new_password']);

if (isset($_SESSION['user_name'])){
$username = $_SESSION['user_name'];

$query_pass = "SELECT user_pass FROM users WHERE user_name = '".$_SESSION['user_name']."'";
$result_set = mysql_query($query_pass) or die(mysql_error());
$pass_rows = mysql_affected_rows($result_set) or die (mysql_error());

$pass_set  = mysql_fetch_array($pass_rows);
while ($pass_set = mysql_fetch_array($result_set)){

        $pass_set['user_id'];
        $pass_set['user_name'];
        $pass_set['user_pass'];

if(empty($old_pass)|| empty($password)|| empty($new_pass)){
echo "ALL THE FIELDS ARE REQUIRED"; 
}
else if ($pass_set['user_pass']!=$old_pass){
echo "PASSWORD DID'NT MATCH!";  
}
else if ($password != $new_pass){
echo "NEW PASS DID'NT MATCH!";
}
else if ($new_pass == $old_pass){
echo "CAN NOT MATCH THE OLD PASSWORD";
}
else {

$salt = time();
$hashedPassword = sha1($new_pass . $salt);

$change_pass = "UPDATE users SET user_pass = '".$hashedPassword."' WHERE user_name = '".$_SESSION['user_name']."'";
$pass_query = mysql_query($change_pass) or die (mysql_error());
if ($pass_query){
echo "Password Changed";
}
else {
echo "Invalid"; 
}
}
}}
}
?>                

<p>&nbsp;</p>
<p>&nbsp;</p>

<div id="content_bottom"></div>


  </div>
</div>
</body>
</html>
Member Avatar for diafol

I'm sorry engrjd91, your formatting is a bit sloppy - no proper indenting - so I'm afraid it's too difficult to read.

I have cleared and indented my code a bit for you.. now is this readable ..
Actually i'm not a professional php coder thats why having stupid problems here:(
Please now check it out. diafol

<?php session_start();
?>
<?php include_once("../includes/connection.php"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Example form</title>
<style type="text/css">
.container1 {
    width: 500px;
    clear: both;
}
.container1 input {
    width: 100%;
    clear: both;
}

</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Change Password</title>
</head>
<body>


<div id="container">
    <div id="header">
        <h1 style="text-align:left">Quality Management<span class="off"> Cell</span></h1>

    </div>   

    <div id="menu">
        <ul>
            <li class="menuitem"><a href="cms.php">Home</a></li>
            <li class="menuitem"><a href="cms-attendance.php">Attendance</a></li>
            <li class="menuitem"><a href="cms-courses.php">Courses</a></li>
            <li class="menuitem"><a href="cms-settings.php">Settings</a></li>

        </ul>
        <a style="text-align:right" href="cms-logout.php">Logout</a>
    </div>

    </div>        
    <div id="content" align="justify">
    <div id="content_top"></div>
    <div id="content_main">
<div id="wrapper">             

<?php
$current_page = $_SERVER['PHP_SELF'];
?>


<form class="login-form" method ="post" action="<?php echo $current_page; ?>">

      <label for="password">Old Password:</label>
      <input name="old_password"/><br /><br />



      <label for="password">New Password:</label>
      <input name="n_password"/><br /><br />



      <label for="password">Confirm new Password:</label>
      <input name="new_password"/><br />

       <p>

        <br />
        <input class="button" name="submit" type="Submit" value="Done"/>

  </form>
<?php

//posting variables!

if(isset($_POST['old_password']) && isset($_POST['n_password']) && isset($_POST['new_password'])){
$old_pass = mysql_real_escape_string($_POST['old_password']);
$password = mysql_real_escape_string($_POST['n_password']);
$new_pass = mysql_real_escape_string($_POST['new_password']);

//defining session variable

if (isset($_SESSION['user_name'])){
$username = $_SESSION['user_name'];

// Passing and reading up the password

$query_pass  = "SELECT user_pass";
$query_pass .= "FROM users";
$query_pass .= "WHERE user_name = '".$_SESSION['user_name']."'";
$result_set = mysql_query($query_pass) or die(mysql_error());
$pass_rows = mysql_affected_rows($result_set) or die (mysql_error());

//reading elements row by row.

$pass_set  = mysql_fetch_array($pass_rows);
while ($pass_set = mysql_fetch_array($result_set)){

$pass_set['user_id'];
$pass_set['user_name'];
$pass_set['user_pass'];

// validating.

                if(empty($old_pass)|| empty($password)|| empty($new_pass)){
                        echo "ALL THE FIELDS ARE REQUIRED"; 
}
                else if ($pass_set['user_pass']!=$old_pass){
                        echo "PASSWORD DID'NT MATCH!";  
}
                else if ($password != $new_pass){
                        echo "NEW PASS DID'NT MATCH!";
}
                else if ($new_pass == $old_pass){
                        echo "CAN NOT MATCH THE OLD PASSWORD";
}
                else {

//if the password is accepted than hashing it.

$salt = time();
$hashedPassword = sha1($new_pass . $salt);

//updating the hashed password.

$change_pass  = "UPDATE users";
$change_pass .= "SET user_pass = '".$hashedPassword."'";
$change_pass .= "WHERE user_name = '".$_SESSION['user_name']."'";

$pass_query = mysql_query($change_pass) or die (mysql_error());

//checking query

            if ($pass_query){
                    echo "Password Changed";
}
            else {
                    echo "Invalid"; 
}
}
}}
}
?>                

<p>&nbsp;</p>
<p>&nbsp;</p>

<div id="content_bottom"></div>


  </div>
</div>
</body>
</html>
Member Avatar for diafol

Sorry - I am here, but busy. I'll check it out tomorrow - in the meantime - anybody else feel free to dive in.

Member Avatar for diafol

I think it's ok, but I'd place all the php processing above the DTD, instead of mixing with html:

<?php 
session_start();
include_once("../includes/connection.php"); 
$msg = '';  
//posting variables!
if(isset($_POST['old_password']) && isset($_POST['n_password']) && isset($_POST['new_password'])){
    $old_pass = mysql_real_escape_string($_POST['old_password']);
    $password = mysql_real_escape_string($_POST['n_password']);
    $new_pass = mysql_real_escape_string($_POST['new_password']);
    //defining session variable
    if (isset($_SESSION['user_name'])){
        $username = $_SESSION['user_name'];
        // Passing and reading up the password
        $query_pass  = "SELECT user_pass";
        $query_pass .= "FROM users";
        $query_pass .= "WHERE user_name = '".$_SESSION['user_name']."'";
        $result_set = mysql_query($query_pass) or die(mysql_error());
        $pass_rows = mysql_affected_rows($result_set) or die (mysql_error());
        //reading elements row by row.
        $pass_set  = mysql_fetch_array($pass_rows);
        while ($pass_set = mysql_fetch_array($result_set)){
            $pass_set['user_id'];
            $pass_set['user_name'];
            $pass_set['user_pass'];
            // validating.
            if(empty($old_pass)|| empty($password)|| empty($new_pass)){
                $msg = "ALL THE FIELDS ARE REQUIRED"; 
            }
            else if ($pass_set['user_pass']!=$old_pass)
            {
                $msg = "PASSWORD DID'NT MATCH!";  
            }
            else if ($password != $new_pass)
            {
                $msg = "NEW PASS DID'NT MATCH!";
            }
            else if ($new_pass == $old_pass)
            {
                $msg = "CAN NOT MATCH THE OLD PASSWORD";
            }
            else
            {
                //if the password is accepted than hashing it.
                $salt = time();
                $hashedPassword = sha1($new_pass . $salt);
                //updating the hashed password.
                $change_pass  = "UPDATE users";
                $change_pass .= "SET user_pass = '".$hashedPassword."'";
                $change_pass .= "WHERE user_name = '".$_SESSION['user_name']."'";
                $pass_query = mysql_query($change_pass) or die (mysql_error());
                //checking query
                if ($pass_query)
                {
                    $msg = "Password Changed";
                }
                else
                {
                    $msg = "Invalid"; 
                }
            }
        }
    }
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Example form</title>
<style type="text/css">
.container1 {
    width: 500px;
    clear: both;
}
.container1 input {
    width: 100%;
    clear: both;
}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="stylesheet" type="text/css" href="style.css" />
<title>Change Password</title>
</head>
<body>
<div id="container">
    <div id="header">
        <h1 style="text-align:left">Quality Management<span class="off"> Cell</span></h1>
    </div>   
    <div id="menu">
        <ul>
            <li class="menuitem"><a href="cms.php">Home</a></li>
            <li class="menuitem"><a href="cms-attendance.php">Attendance</a></li>
            <li class="menuitem"><a href="cms-courses.php">Courses</a></li>
            <li class="menuitem"><a href="cms-settings.php">Settings</a></li>
        </ul>
        <a style="text-align:right" href="cms-logout.php">Logout</a>
    </div>
    </div>        
    <div id="content" align="justify">
    <div id="content_top"></div>
    <div id="content_main">
<div id="wrapper">             
<?php
$current_page = $_SERVER['PHP_SELF'];
?>
<form class="login-form" method ="post" action="<?php echo $current_page; ?>">
      <label for="password">Old Password:</label>
      <input name="old_password"/><br /><br />
      <label for="password">New Password:</label>
      <input name="n_password"/><br /><br />
      <label for="password">Confirm new Password:</label>
      <input name="new_password"/><br />
       <p>
        <br />
        <input class="button" name="submit" type="Submit" value="Done"/>
  </form>
  <?php echo $msg;?>
<p>&nbsp;</p>
<p>&nbsp;</p>
<div id="content_bottom"></div>
  </div>
</div>
</body>
</html>

Was there a problem with it?

You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'user_name = 'engrjd'' at line 1

having this error, with your code.

I have resolved it, not having..

Warning: mysql_affected_rows(): supplied resource is not a valid MySQL-Link resource in

Warning: mysql_affected_rows(): supplied resource is not a valid MySQL-Link resource in C:\xampp\htdocs\fyp\cms\cms-settings.php on line 19

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.