Изменить пароль в PHP - PullRequest
       5

Изменить пароль в PHP

0 голосов
/ 24 марта 2012

У меня есть скрипт смены пароля в PHP, и я хочу сделать, это взять переменные из предыдущего экрана, которые вводит пользователь, а затем сравнить их с MySQL базы данныхЕсли старый пароль не совпадает с тем, что они вставили, я хочу, чтобы он потерпел неудачу с ошибкой.Это код, который у меня есть до сих пор ... но я знаю, что сравнение строки с переменной не сработает, но нужно знать, как преобразовать их, чтобы они могли сравнивать.Ниже находится рассматриваемая страница.

Пароли в настоящее время хранятся в формате простого текста на БД, но позже они изменятся на md5.Вопрос в том, как сравнить введенное значение со значением, полученным из БД?

<html>
<head>
<title>Password Change</title>
</head>
<body>

<?php

mysql_connect("localhost", "kb1", "BajyXhbRAWSVKPsA") or die(mysql_error());
mysql_select_db("kb1") or die(mysql_error());

    $todo=mysql_real_escape_string($_POST['todo']);
    $username=mysql_real_escape_string($_POST['userid']); 
    $password=mysql_real_escape_string($_POST['password']);
    $password2=mysql_real_escape_string($_POST['password2']);
    $oldpass=mysql_real_escape_string($_POST['oldpass']);

/////////////////////////

if(isset($todo) and $todo == "change-password"){
//Setting flags for checking
$status = "OK";
$msg="";

//MYSQL query to pull the current password from the database and store it in  $q1

$results = mysql_query("SELECT password FROM kb_users WHERE username = '$username'") or             die(mysql_error());  
$q1 = mysql_fetch_array($results);
//print_r($q1)


//changing the string $oldpass to using the str_split which converts a string to an     array.

//$oldpass1 = str_split($oldpass,10);

if(!$q1)  

    {  
        echo "The username <b>$username</b> does not exist in the database.  Please         click the retry button to attempt changing the password again. <BR><BR><font face='Verdana'     size='2' color=red>$msg</font><br><center><input type='button' value='Retry'     onClick='history.go(-1)'></center>"; die();
    }  

if ($oldpass == $q1){

$msg = $msg.  "The provided password <b>$oldpass</b> is not the same as what is in the     database. Please click the retry button to attempt changing the password again.<BR><br>";

$status = "NOTOK";} 
/*
if ($q1 <> $oldpass1) {    
$msg = $msg.  "The provided password <b>$oldpass</b> is not the same as what is in the     database. Please click the retry button to attempt changing the password again.<BR><br>";
$status = "NOTOK";  }
*/

if ( strlen($password) < 3 or strlen($password) > 10 ){
$msg=$msg.  "Your new password must be more than 3 char legth and a maximum 10 char     length<BR><BR>";
$status= "NOTOK";}                  

if ( $password <> $password2 ){
$msg=$msg.  "Both passwords are not matching<BR>";
$status= "NOTOK";}                  


if($status<>"OK")
    { 
        echo "<font face='Verdana' size='2' color=black>$msg</font><br><center>    <input type='button' value='Retry' onClick='history.go(-1)'></center>";
    }
        else {
        // if all validations are passed.

            if (mysql_query("UPDATE kb_users SET password='$password' where         username='$username'") or die(mysql_error())); 

                {
                    echo "<font face='Verdana' size='2' ><center>Thanks     <br> Your password has been changed successfully. Please keep changing your password for     better security</font></center>";
                }
            }
        }


?>      
</body>
</html>

1 Ответ

1 голос
/ 24 марта 2012

Прежде всего, не рекомендуется использовать данные POST непосредственно в запросе.Вам лучше сначала избежать этих данных, чтобы избежать инъекций.

Кроме того, я думаю, ваш способ использования if - не лучший способ.На мой взгляд, нет необходимости в переменной состояния.Это точно в этом случае.$status устанавливается на NOTOK непосредственно перед проверкой его значения.Так что это всегда будет NOTOK, что приведет к тому, что ваш скрипт никогда не обновит пароль.

Я изменил структуру ваших тестов, чтобы, на мой взгляд, лучше.Внимательно посмотрите на то, что вы хотели бы проверить, потому что теперь все ваши тесты перепутаны.

<html>
<head>
    <title>Password Change</title>
</head>

<body>

    <?php
        // MySQL connection details

        $todo=mysql_real_escape_string($_POST['todo']);
        $username=mysql_real_escape_string($_POST['userid']); 
        $password=mysql_real_escape_string($_POST['password']);
        $password2=mysql_real_escape_string($_POST['password2']);
        $oldpass=mysql_real_escape_string($_POST['oldpass']);

        if(isset($todo) and $todo == "change-password"){

            $results = mysql_query("SELECT password FROM kb_users WHERE username = '$username'") or             die(mysql_error());  
            $q1 = mysql_fetch_array($results);

            if (!$q1) {
                // The user does not exist in the database. 
            }

            if ($oldpass == $q1) {
                // The current password matches the input from the oldpass field.

                if (strlen($password) > 3 or strlen($password) < 10) {
                    // Password meets requirements
                    if ($password == $password2) {
                        //Passwords match, update the password in the database
                    }
                    else {
                        // The new passwords do not match.
                    }
                }
                else {
                    // Password is too short / long
                }

            }
        }
    ?>
</body>

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...