0

So I'm trying to add a password reset functionality on a login form using php, MySQL and using a UwAmp server. This has to be done this way as I'll need to place the project on a university UwAmp filespace that is accessible to my lecturers etc.

I've tried the code below, however, obviously, it's not sending an email. Will I have to install a mail client to send something to an email account? Or is this something that can't really be done on a localhost and I should instead mimic the email functionality on a separate page?

<?php 
    error_reporting(0);
    require_once 'config.php';
    if (isset($_POST['email'])) {
        $email = $_POST['email'];
        $code = rand(100,999);
        $query = "SELECT * FROM `userdetails` WHERE email = '$email'";
        $result = mysqli_query($link,$query) or die(mysqli_error());
        $count = mysqli_num_rows($result);

        if ($count == 1) {
            mysqli_query("update userdetails set activation_code='$code' where email='$email'");

               //send email
$to = "$email";
$subject = "Account Details Recovery";
$body = "Hi $r->email, nn you or someone else have requested your account details. nn Here is your account information please keep this as you may need this at a later stage. nnYour username is $r->email nn your password is $password nn Your password has been reset please login and change your password to something more rememberable.nn Regards Site Admin";
$lheaders= "From: <contact@domain.com>rn"; //is this where i should place my own email address?
$lheaders.= "Reply-To: noprely@domain.com";
mail($to, $subject, $body, $additionalheaders);
        } else {
        }
        echo " Something Here for a response";
    }
?>

<form action="" method="post">
    Enter you email ID: <input type="text" name="email">
    <input type="submit" name="submit" value="Send">
</form>

Reset pass. Not being used as yet, also contains some errors like not using my $link variable from my config file, just included to show what i'm trying.

<?

include'config.php';
if(isset($_GET['action']))
{          
    if($_GET['action']=="reset")
    {
        $encrypt = mysqli_real_escape_string($connection,$_GET['encrypt']);
        $query = "SELECT id FROM users where md5(90*13+id)='".$encrypt."'";
        $result = mysqli_query($link,$query);
        $Results = mysqli_fetch_array($result);
        if(count($Results)>=1)
        {

        }
        else
        {
            $message = 'Invalid key please try again. <a href="http://demo.phpgang.com/login-signup-in-php/#forget">Forget Password?</a>';
        }
    }
}
elseif(isset($_POST['action']))
{

    $encrypt      = mysqli_real_escape_string($connection,$_POST['action']);
    $password     = mysqli_real_escape_string($connection,$_POST['password']);
    $query = "SELECT id FROM users where md5(90*13+id)='".$encrypt."'";

    $result = mysqli_query($connection,$query);
    $Results = mysqli_fetch_array($result);
    if(count($Results)>=1)
    {
        $query = "update users set password='".md5($password)."' where id='".$Results['id']."'";
        mysqli_query($connection,$query);

        $message = "Your password changed sucessfully <a href=\"http://demo.phpgang.com/login-signup-in-php/\">click here to login</a>.";
    }
    else
    {
        $message = 'Invalid key please try again. <a href="http://demo.phpgang.com/login-signup-in-php/#forget">Forget Password?</a>';
    }
}
else
{
    header("location:login.php");
}

Login form

<?php

//Login file, log the user checking for correct details


 require_once 'config.php';//Connect to the database


// Define variables and initialize with empty values
$email = $password = "";
$user_err = $pass_err = "";


if($_SERVER["REQUEST_METHOD"] == "POST"){

    // Check if email is empty
    if(empty(trim($_POST["email"]))){
        $user_err = 'Please enter email.';
    } else{
        $email = trim($_POST["email"]);
    }

    // Check if password is empty
    if(empty(trim($_POST['password']))){
        $pass_err = 'Please enter your password.';
    } else{
        $password = trim($_POST['password']);
    }

    // Validate credentials
    if(empty($user_err) && empty($pass_err)){

        // Prepare a select statement
        $sql = "SELECT email, password FROM userdetails WHERE email = ?";

        if($stmt = mysqli_prepare($link, $sql)){
            // Bind variables to the prepared statement as parameters
            mysqli_stmt_bind_param($stmt, "s", $param_email);

            // Set parameters
            $param_email = $email;

            // Attempt to execute the prepared statement
            if(mysqli_stmt_execute($stmt)){
                // Store result
                mysqli_stmt_store_result($stmt);

                // Check if email exists, if yes then verify password
                if(mysqli_stmt_num_rows($stmt) == 1){                    
                    // Bind result variables
                    mysqli_stmt_bind_result($stmt, $email, $hashed_password);
                    if(mysqli_stmt_fetch($stmt)){
                        if(password_verify($password, $hashed_password)){
                            /* Session start here to stop users from accessing 
                            welcome page before signing in with valid details*/
                            session_start();
                            $_SESSION['email'] = $email;      
                            header("location: welcomePage.php");
                        } else{
                            // Display an error message if password is not valid
                            $pass_err = 'The password you entered was not valid.';
                        }
                    }
                } else{
                    // Display an error message if email doesn't exist
                    $user_err = 'No account found with that email.';
                }
            } else{
                echo " Something went wrong. Please try again later.";
            }
        }

        // Close statement
        mysqli_stmt_close($stmt);
    }

    // Close connection
    mysqli_close($link);
}


?>

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="utf-8">

    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Login Page</title>
    <link rel="stylesheet" href="css/style.css">
    <script src="js/script.js"></script>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
  </head>
  <body>





      <div class="parent">

      <div class="form_login">

               <h2 class="title">Sign in</h2>


<form name ="credentials" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>" method="post" onsubmit="return validateForm()" onKeyPress="return checkSubmit(event)">
            <div class="formGroups">

                <input type="text" pattern="[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{1,63}$" name="email" class="form-control" placeholder="email">
                <span id="errmsg"><?php echo $user_err; ?></span>
            </div>    
            <div class="formGroups">

                <input type="password" name="password" class="form-control" placeholder="password">
                <span id="errmsg"><?php echo $pass_err; ?></span>
            </div>
            <div class="form-group">
                <input type="submit" class="btn btn-primary" value="Submit">
                <input type="reset" class="btn btn-default" value="Reset">
            </div>
            <p>Not got an account? <a href="register.php">Register for a new account here</a>.</p>
            <p>Forgot Password? <a href="send_link.php">Reset it here</a></p>
        </form>


          </div>




      </div>


  </body>
</html>
Sujal Patel
  • 2,444
  • 1
  • 19
  • 38
  • 5
    While you are in there... you'll want to ditch using `md5` for passwords, and utilize `password_hash` and `password_verify`. – IncredibleHat Mar 22 '18 at 13:52
  • 3
    So this wall of code could be simply summarised as "how do I send an email on localhost" ? .. which I'm 99% certain will have already been asked before. – CD001 Mar 22 '18 at 13:54
  • it is normal that `mail ()` won't work on localhost. to accomplish that you need to set up a mail server. look here for more informations. https://stackoverflow.com/questions/5342822/php-mail-function-on-localhost – wayneOS Mar 22 '18 at 13:54
  • Consider using `filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)` to check that it's a valid email. I would also still escape it (you seem to have forgotten it in the first block) – Andy Mar 22 '18 at 13:57
  • There are a lot of results by searching for "php mail from localhost". If you don't want to install a local email server, you could use something like PHPMailer to send through smtp and a gmail account for example. – IncredibleHat Mar 22 '18 at 14:00
  • Personally, I like to use the PHPConsole server library to debug, and label messages. (in combination with the Google Chrome plugin) Debug tagged 'email' and the output is just raw html but that's fine for me. Make it so that it will be disabled in production. – twicejr Mar 22 '18 at 14:00
  • Take care: sending mail from localhost outbound is a guarantee for problems here in my province. (without having a domain, a PTR record for rDNS and using DKIM) Did so once, got blocked because they thought it was malicious activity from a trojan horse. – twicejr Mar 22 '18 at 14:04
  • Okay, thankyou very much everyone for the advice and even the people who opted for the normal stack overflow passive-aggressive advice. I'll take a look at a proper mail server. –  Mar 22 '18 at 14:10

0 Answers0