-2

I am trying to figure out why my check database for same username is not running because the code is right but its just not running properly reason why I know the code is right for the query because my email one is working so I think the problem is how I put the query on the page but I am moving it all over the place to see if it works and it just seems to not.

<?php
//Declare Feedback Error Messages for Each Field on Member Registration Form
  $userErr = "";
  $emailErr = "";
  $passErr = "";
  $capErr = "";
//Get Post Values from form
  $user = $_POST['username'];
  $pass = $_POST['password'];
  $em = $_POST['email'];
  $confirm_code= getCode(5);
  $status = 0;
//Encode value for email and Code.
  $email_encoded = rtrim(strtr(base64_encode($em), '+/', '-_'), '=');
  $code_encoded = rtrim(strtr(base64_encode($confirm_code), '+/', '-_'), '=');
  //$code_decoded = base64_decode(strtr($codenum, '-_', '+/'));



  include_once 'securimage/securimage.php';
  $cVal = new Securimage();
  //validate data
    validate($user, $pass, $em, $cVal);
  if ($userErr != "" || $emailErr!= "" || $passErr!= "" || $capErr!="") {
  Header("Location:../presentation/memberRegistration.php?userMsg=$userErr&passMsg=$passErr&emailMsg=$emailErr&capMsg=$capErr");
}else {
      sanitize($user);
        sanitize($pass);
      sanitize($em);
      $encodedpass= md5($pass);
      //include connection string
  include("../data/dbConnection.php");
    $found = false;
    if ($stmt = mysqli_prepare($mysqli, "SELECT * FROM tblMember WHERE email=?"))
            {
                //bind parameters for markers
                mysqli_stmt_bind_param($stmt, "s", $em);
                //execute query
                mysqli_stmt_execute($stmt);
                //store result
                mysqli_stmt_store_result($stmt);
                //get the number of rows returned
                $test = mysqli_stmt_num_rows($stmt);
                //if no results found
                if($test !=0)
                {
                    $emailErr = "Email Address Already Exists";
                    Header("Location:../presentation/memberRegistration.php?emailMsg=$emailErr");
                }
                else
                {
                    $found = true;
                }
                //close statement
                mysqli_stmt_close($stmt);
            }
            //close connection
                    mysqli_close($mysqli);
          if ($found == true) {
          include("../data/dbConnection.php");
          if ($stmt = mysqli_prepare($mysqli, "SELECT * FROM tblMember WHERE username=?"))
            {
              //bind parameters for markers
              mysqli_stmt_bind_param($stmt, "s", $user);
              //execute query
              mysqli_stmt_execute($stmt);
              //store result
              mysqli_stmt_store_result($stmt);
              //get the number of rows returned
              $test1 = mysqli_stmt_num_rows($stmt);
              //if no results found
              if($test1 !=0)
              {
                $userErr = "Username already Exists";
                Header("Location:../presentation/memberRegistration.php?userMsg=$userErr");
              }
              else
              {
                $found = true;
              }
              //close statement
              mysqli_stmt_close($stmt);
            }
            //close connection
                mysqli_close($mysqli);
          }

if ($found == true) {
        include("../data/dbConnection.php");
    if ($stmt = mysqli_prepare($mysqli, "INSERT INTO tblMember(username, password, email, code, status) VALUES (?, ?, ?, ?, ?)"))
    {//bind parameters to the statement object

        mysqli_stmt_bind_param($stmt, "ssssi", $user, $encodedpass, $em,  $confirm_code, $status);
        $feedback = "";
        if(mysqli_stmt_execute($stmt)){
      //Call to Send Email.
            sendEmail($em, $confirm_code, $email_encoded);
            $feedback = "Your Registration has been successful and <p>Your Confirmation link Has Been Sent To Your Email Address..";
            Header("Location:sendEmail.php?feedbackMsg=$feedback&confirmCode=$code_encoded&em=$email_encoded");
        }else{
            $feedback.= "Your Registration has been unsuccessful.";
            Header("Location:../presentation/memberRegistration.php?feedbackMsg=$feedback");
        }
    }

}

}

//Email
function sendEmail($email, $code, $encodeEmail){


$to=$email;


$subject="Activation Link For Your Account";


$header = "MIME-Version: 1.0" . "\r\n";
$header .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$header .="From:WAD<sheena.s.sylvester@gmail.com>";


$message = "
<html>
<head>
<title>HTML email</title>
</head>
<body style='background-color:red'>
 <h2 bgcolor='#0099ff'><i>Your Activation Link</i></h2>
 <p>Hey Here is your Activation Code:$code

 <br/>Please click on the link below to activate your account status</p>
 <a href='http://localhost/royalGreenwhich/php/logic/sendEmail.php?confirmCode=$code&em=$encodeEmail'>Click Here</a> To activate your account.
</body>
</html>";

// send email using PHP mail function
ini_set("smtp_port","25");
$sentmail = mail($to,$subject,$message,$header);

// if your email succesfully sent
if($sentmail){
 echo "<p>Your Confirmation link Has Been Sent To Your Email Address.";
}
else {
 echo "Cannot send Confirmation link to your e-mail address";
}

}


function getCode($len){
      $result = "";
      $chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
      $charArray = str_split($chars);
      for($i = 0; $i < $len; $i++){
        $randItem = array_rand($charArray);
        $result .= "".$charArray[$randItem];
      }
      return $result;
  }
//Function to SANITIZE (Clean) datax`
function sanitize($data){
  $data = trim($data);
  $data = stripslashes($data);
  $data = filter_var($data, FILTER_SANITIZE_SPECIAL_CHARS);
  $data = filter_var($data, FILTER_SANITIZE_STRING);
  $data = filter_var($data, FILTER_SANITIZE_STRING);
  $data = filter_var($data, FILTER_SANITIZE_STRING);

  //for,at data for storage (maintain uniformity)
  $data = strtolower($data);
  $data = ucfirst($data);

  return $data;
}//end sanitize function

  function validate($userVal, $passVal, $emVal, $cVal){
        global $userErr;
        global $passErr;
        global $emailErr;
        global $capErr;
        $valid = true;

    if($userVal == null || $userVal == ""){
      $userErr = "Username Field  required.";
            $valid = false;
    }

    if($passVal == null || $passVal == ""){
      $passErr = "Password Field  required.";
            $valid = false;
    }

    if($emVal == null || $emVal == ""){
      $emailErr = "Email Field required.";
            $valid = false;
    }

    if ($cVal->check($_POST['captcha_code']) == false){
            $capErr .= "Please try again. <br/>You have inserted the wrong Captcha";
            $valid = false;
        }

return true;
}
 ?>
  • 2
    ***You really shouldn't use [MD5 password hashes](http://security.stackexchange.com/questions/19906/is-md5-considered-insecure)*** and you really should use PHP's [built-in functions](http://jayblanchard.net/proper_password_hashing_with_PHP.html) to handle password security. Make sure you [don't escape passwords](http://stackoverflow.com/q/36628418/1011527) or use any other cleansing mechanism on them before hashing. Doing so *changes* the password and causes unnecessary additional coding. – Jay Blanchard Apr 06 '17 at 19:41
  • 2
    @JayBlanchard They wants dah codes/answer/solution. They probably don't give much care to security. Who cares about security anyway? Just as long as nobody busts in with Lord knows what in their hands. – Funk Forty Niner Apr 06 '17 at 19:49
  • *"its just not running properly"* is not a very specific description of the issue you're experiencing. There is also no specific question. You might want to check up on [ask]. – domsson Apr 07 '17 at 01:36

2 Answers2

0

Both of your database check queries are doing the same check WHERE email=?. If you want to check for uniqueness of username, you need to change your second query to be

        if ($stmt = mysqli_prepare($mysqli, "SELECT * FROM tblMember WHERE username=?"))

Another way to do this could also be to utilise your DBMS' unique field property: SQL UNIQUE. Attempt the insert with supplied username and email and handle the error that comes back and report it to the user if required.

domwrap
  • 443
  • 1
  • 4
  • 12
0

Your sql statement for selecting the user is the same as the one for email (the condition is based on email column). It seems like a copy-paste error...

Not commenting on the rest of the code (as there is quite a lot to check) I would suggest to strongly consider creating a new function as soon as there is a temptation to copy-paste. Event if it requires some additional work and creativity to write a modular function, there are benefits too. It is less error prone (usually fewer lines of code mean smaller chance of a mistake). The readability improves (if you comment your code with proper explanations).

EDIT:

There seems to be a logical error. You use a single variable for indicating $found. If you do not find an email, $found = true. This does not change regardless of finding a duplicate user. Therefore no matter what the user check, if the email is ok, you execute this part of code:

if ($found == true) {
        include("../data/dbConnection.php");
    if ($stmt = mysqli_prepare($mysqli, "INSERT INTO tblMember(username, password, email, code, status) VALUES (?, ?, ?, ?, ?)"))
    {//bind parameters to the statement object

        mysqli_stmt_bind_param($stmt, "ssssi", $user, $encodedpass, $em,  $confirm_code, $status);
        $feedback = "";
        if(mysqli_stmt_execute($stmt)){
      //Call to Send Email.
            sendEmail($em, $confirm_code, $email_encoded);
            $feedback = "Your Registration has been successful and <p>Your Confirmation link Has Been Sent To Your Email Address..";
            Header("Location:sendEmail.php?feedbackMsg=$feedback&confirmCode=$code_encoded&em=$email_encoded");
        }else{
            $feedback.= "Your Registration has been unsuccessful.";
            Header("Location:../presentation/memberRegistration.php?feedbackMsg=$feedback");
        }
    }

}

I suggest you use two different variables for email and user ($email_not_found, $user_not_found) and then check for both of them. Or if you find an existing user, you change the $found back to false. Also consider changing the $found to something else as the variable name indicates (at least to me) that the mail/user was found, but is used in the opposite manner ($found = true when user/email do not exist).

Viliam Aboši
  • 447
  • 2
  • 14