Неопределенный индекс для переменных GET при попытке создать страницу сброса пароля в PHP - PullRequest
0 голосов
/ 22 ноября 2011

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

Однако, когда я иду, чтобы сменить пароль, я получаю следующие ошибки

Notice: Undefined index: email in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\reset-password.php on line 112

Notice: Undefined index: hash in C:\Program Files\Apache Software Foundation\Apache2.2\htdocs\reset-password.php on line 112

Это мой код для reset-password.php ...

<?php
$msg = "";

    // If user is visiting using the link provided in the email
    if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['hash']) && !empty($_GET['hash']))
        {  
        $email = checkInput($_GET['email']); // Set email variable  
        $hash = checkInput($_GET['hash']); // Set hash variable  

        $search = mysql_query("SELECT email, hash FROM users WHERE email='".$email."' AND hash='".$hash."'") or die(mysql_error());  
        $match  = mysql_num_rows($search);  


        if($match > 0)
            {  
            // There is a match -> show change password form
            changePassForm();
            }
        else
            {  
            // No match -> dont show password form (invalid url)
            $msg .= '<div class="success" align="center">An email with a link to reset your password has been sent to your registered email account. Please click the link to reset your password.</div>';
            }  

        }
    // Else user is not visting from a link provided in an email.
    else
        // First check if user has already submitted form to send change password link
        {
        if(isset($_POST['submit-request']))
            {
            $username = checkInput($_POST['username']); 
            $query = "SELECT username FROM users WHERE username = '$username'";
            $result = mysql_query($query);
            $search = mysql_num_rows($result);
            // Checks if the username they entered exists - if so, call sendResetMail function. 
            if($search > 0)
                {
                $msg .= '<div class="success" align="center">An email with a link to reset your password has been sent to your registered email account. Please click the link to reset your password.</div>';  
                sendResetMail(); // Calls the sendMail function - sends the activation email to the user.
                }
            // Else username does not exist in database
            else
                {
                $msg .= '<div class="error" align="center">That username does not exist. Please try again.</div>';
                requestForgotPassEmail();
                }
            }
        // If user has not already submitted form, show them form.
        else
            {
            requestForgotPassEmail();
            $msg .= "request email";
            }
        }





    /* Initialize  empty containers for the errors */
    $rpnewpass_errors = "";
    $rpnewpasschk_errors = "";
    $msg = "";


    // If changePassForm has been submitted
    if(isset($_POST['submit-change']))
        {
        $newpass=isset($_POST['newpass']) ? checkInput($_POST['newpass']) : '';
        $newpasschk=isset($_POST['newpasschk']) ? checkInput($_POST['newpasschk']) : '';


        /* Checks all fields were entered */  
        if(!$_POST['newpass'] || !$_POST['newpasschk'])
            {
            $msg .= '<div class="error" align="center">You didn\'t a required field - please complete all the fields</div>';
            }

        else
            {
            /* Once all fields are entered - perform form validation */

            /* Checks the new password field is entered */      
            if(empty($newpass))
                {
                $newpass=false;
                $rpnewpass_errors .= "You didn't enter a new password";
                }

            /* Checks if the password contains at least 8 characters, lower/upper case letters and a number. */
            if(preg_match("/^.*(?=.{8,})(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z]).*$/", $newpass) === 0)
                {
                $msg .= '<div class="error" align="center">Password must be at least 8 characters and contain at least one lower case letter, one upper case letter and a number</div>';
                }

            /* Checks the verify new password field is entered */
            if(empty($newpasschk))
                {
                $msg .= '<div class="error" align="center">You didnt verify your new password.</div>';
                }

            /* Checks if the new password and verify new password match */
            if($newpass != $newpasschk)
                {
                $msg .= '<div class="error" align="center">Sorry, your passwords do not match.</div>';
                }

            /* Checks if all error containers are empty, then proceeds with password change */
            if(empty($rpnewpass_errors) && empty($rpnewpasschk_errors))
            {
            $query="SELECT username FROM users WHERE email = '$email' AND hash = '$hash'";
            echo $query; // for troubleshooting purposes, variables are echoing empty
            $result=mysql_query($query);
            $num=mysql_num_rows($result);

            if($num == 1)
                {
                $row=mysql_fetch_array($result);
                $md5newpass=md5($newpass);
                $query="UPDATE users SET password = '$md5newpass' WHERE username = '$row[0]'";
                $result=mysql_query($query);

                if(mysql_affected_rows() == 1) 
                    {
                    $msg .= '<div class="error" align="center">Your password has been changed successfully</div>';
                    }

                else
                    {
                    $msg .= '<div class="error" align="center">Your password could not be changed. Please try again</div>';
                    }
                    }
                else
                    {
                    $msg .= '<div class="error" align="center">Your username and password do not match our records</div>';
                    }
                }
            }
        }





?>

Я предполагаю, что где-то / как-то теряю переменные GET из ссылки, но не уверен, как мне обойти это - это был долгий день, и я застрял на этом некоторое время, поэтому извиняюсь за любую очевидную ошибку !

Спасибо.

1 Ответ

0 голосов
/ 22 ноября 2011

Вы положили $ email и $ hash в этой строке?

    $query="SELECT username FROM users WHERE email = '$email' AND hash = '$hash'";
    echo $query; // for troubleshooting purposes, variables are echoing empty

Вы устанавливаете это здесь, но только в условном выражении:

if(isset($_GET['email']) && !empty($_GET['email']) AND isset($_GET['hash']) && !empty($_GET['hash']))

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

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