I'm trying to make a script that changes an encrypted password inside a MySQL table. I think the code is correct, but the script isnt changing the password. It does detect when the old password is wrong and when the new password doesnt match the conformation password. When everything checks out, it doesnt give an error and just redirects.
try
{
$db = new PDO("mysql:host={$host};dbname={$dbname};charset=utf8", $username, $password, $options);
}
catch(PDOException $ex)
{
die("Failed to connect to the database: " . $ex->getMessage());
}
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$db->setAttribute(PDO::ATTR_DEFAULT_FETCH_MODE, PDO::FETCH_ASSOC);
if(function_exists('get_magic_quotes_gpc') && get_magic_quotes_gpc())
{
function undo_magic_quotes_gpc(&$array)
{
foreach($array as &$value)
{
if(is_array($value))
{
undo_magic_quotes_gpc($value);
}
else
{
$value = stripslashes($value);
}
}
}
undo_magic_quotes_gpc($_POST);
undo_magic_quotes_gpc($_GET);
undo_magic_quotes_gpc($_COOKIE);
}
header('Content-Type: text/html; charset=utf-8');
session_start();
if(!empty($_SESSION['user']))
unset ($_SESSION['user']);
if(!empty($_POST))
{
$query = "
SELECT
username,
password,
salt
FROM users
WHERE
username = :username
";
$query_params = array(
':username' => $_POST['username']);
try
{
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex)
{
die("Failed to run query: " . $ex->getMessage());
}
$pass = false;
$row = $stmt->fetch();
if($row)
{
$check_password = hash('sha256', $_POST['old'] . $row['salt']);
for($round = 0; $round < 65536; $round++)
{
$check_password = hash('sha256', $check_password . $row['salt']);
}
if($check_password !== $row['password'])
{
die("Incorrect old password!");
}
if($_POST['new'] !== $_POST['confirm'])
{
die("Password does not match!");
}
$pass = true;
}
if($pass)
{
$salt = dechex(mt_rand(0, 2147483647)) . dechex(mt_rand(0, 2147483647));
$password = hash('sha256', $_POST['new'] . $salt);
for($round = 0; $round < 65536; $round++)
{
$password = hash('sha256', $password . $salt);
}
$query1 = " UPDATE users SET password = ':password', salt = ':salt' WHERE username = ':username' ";
$query_params1 = array(
':username' => $_POST['username'],
':password' => $password,
':salt' => $salt
);
try
{
$stmt1 = $db->prepare($query1);
$result1 = $stmt1->execute($query_params1);
}
catch(PDOException $e)
{
die("Failed to run query: " . $e->getMessage());
}
header("Location: index.php");
die;
}
else
{
print("Password change failed.");
}
}