-1

I am working on a simple registration system and after hours of research am still stuck.

If my database is clear (I delete any rows in the table), and I submit the form, it sends a validation email and activates and allows me to login.

If I try to create another account with the same email, I am not getting my error message like I should be, telling the user "the email has already been registered." It just takes me to a blank page, even if I use a new email address after the first row has been created.

When I look at my table, the row created by the form (the first time) has the auto-inc ID which is right, the username is input into the row, but password, email, and activation all say '0'.

Can anyone see where the error is in my code? I need the code to verify that the email entered isn't already used, and if it is, to display the errormessage. If it isn't, it should be creating a new row in the table with the information.

I know I need to hash the password. I'm just trying to get the information in the table right before I proceed with security.

index.php

<?php

    include 'sessions.php';

    if(isset($_SESSION['errormessage'])){   
        echo ($_SESSION['errormessage']);
        unset ($_SESSION['errormessage']);
    }
?>

<html>
<head>
  <title>Registration Form</title>
</head>

<body>
  <form name="newForm" method="post" action="createaccount.php">UserName:
    <input type="text" name="newUserName" size="15" maxlength="15">
    <br>Password:
    <input type="password" name="newPass1" size="15">
    <br>Confirm Password:
    <input type="password" name="newPass2" size="15">
    <br>Email:
    <input type="email" name="newEmail" size="15">
    <br>
          <input type="submit" name="newSubmit">
          <input type="reset" name="newReset">
        </p>
  </form>

 <hr>

    <form name="newForm" method="post" action="login.php">
        <strong>Already Registered? Login Here:</strong>
        <br>
    UserName:
    <input type="text" name="UserName" size="15" maxlength="15">
    <br>Password:
    <input type="password" name="Pass1" size="15">
    <br>        
        <input type=submit name=SubmitButton value=Submit>
        <input type=reset name=ResetButton value=Clear>
    </form>     

</body>

</html>

createaccount.php

<?php

    include ('sessions.php');
    include ('database_connection.php');

//function to test password
function passwordStrength($pwd) {
    //test for at least 8 characters
    if (strlen($pwd) < 8) {
        return false;
    }
    //test for max length
    if (strlen($pwd) > 16) {
        return false;
    } 
    //test to see if password contains number
    if(!preg_match("#[0-9]+#", $pwd)) {
        return false;
    }
    //test to see if password has capital letter
    if(!preg_match("#[A-Z]+#", $pwd)) {
        return false;
    }
    //test to see if password has a lowercase letter
    if(!preg_match("#[a-z]+#", $pwd)) {
        return false;
    }
    //test to see if password has special character
    if(!preg_match("#[^0-9A-Za-z]#", $pwd)) {
        return false;
    }
    //test to see if password contains a space
    if (strpos($pwd, ' ') > 0) {
        return false;
    }
    else {
        return true;
    }

    return true;
}

    if(isset($_POST['newSubmit'])){
            if(empty($_POST['newUserName'])) {
            $_SESSION['errormessage'] = "Please enter a username!";
            header("Location: index.php");
            } 
            else if (strlen($_POST['newUserName']) < 4) {
                $_SESSION['errormessage'] = "Username is too short!";
                header("Location: index.php");
            } else if(strlen($_POST['newUserName']) > 16) {
                $_SESSION['errormessage'] = "Username is too long!";
                header("Location: index.php");
            } else if(empty($_POST['newPass1'])) {
                $_SESSION['errormessage'] = "You must enter a password!";
                header("Location: index.php");
            } else if(empty($_POST['newPass2'])) {
                $_SESSION['errormessage'] = "You must confirm your password!";
                header("Location: index.php");
            } else if($_POST['newPass1'] !== $_POST['newPass2']) {
                $_SESSION['errormessage'] = "Passwords do not match!";
                header("Location: index.php");
            } else if(!passwordStrength($_POST['newPass1'])) {
                $_SESSION['errormessage'] = "Password does not meet requirements!";
                header("Location: index.php");
            } else if(empty($_POST['newEmail'])) {
                $_SESSION['errormessage'] = "Must enter an email address!";
                header("Location: index.php");
            }   else {
                $Email = $_POST['newEmail'];
                $name = $_POST['newUserName'];
                $Password = $_POST['newPass1'];
                //echo "All fields accepted!";
                //$pwd = $_POST['newPass1'];
                //echo hash("sha256", $pwd);
                // Make sure the email address is available:
                $query_verify_email = "SELECT * FROM userDB WHERE email ='$Email'";
                $result_verify_email = mysqli_query($db, $query_verify_email);
                if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
                    $_SESSION['errormessage'] = "Sorry, that email address has already been registered!<br />If you already have an account, login below.<br /><br />";
                    header("Location: index.php");
                }

                if (mysqli_num_rows($result_verify_email) == 0) { // IF no previous user is using this email .


                    // Create a unique  activation code:
                    $activation = md5(uniqid(rand(), true));


                    $query_insert_user = "INSERT INTO `userDB` ( `username`, `email`, `password`, `activation`) VALUES ( '$name', '$Email', '$Password', '$activation')";


                    $result_insert_user = mysqli_query($db, $query_insert_user);
                if (!$result_insert_user) {
                    echo 'Query Failed ';
                }

                if (mysqli_affected_rows($db) == 1) { //If the Insert Query was successfull.
                    //send the email
                    $to = $_POST['newEmail']; // this is your Email address
                    $from = "mtshort87@gmail.com"; // this is the sender's Email address
                    $subject = "Account Succesfully Created";
                    $message = "Thank you for creating an account. Please activate it now using the link below!";
                    $message2 = "http://cts.gruv.org/short/form/activate.php?username=".$_POST['newUserName']."\n";
                    $headers = "From:" . $from;
                    $headers2 = "From:" . $to;
                    mail($to,$subject,$message2,$message,$headers);
                    mail($from,$subject,$message2,$message,$headers); // sends a copy of the message to the sender
                        $_SESSION['errormessage'] = "A confirmation e-mail has been sent to you. Please activate your account to login.";
                        header("Location: index.php");
                }
                mysqli_close($db);//Close the DB Connection
            }
        }
    }

activate.php

<?php

include 'sessions.php';
include 'database_connection.php';

if (isset($_GET['Email']) && preg_match('/^([a-zA-Z0-9])+([a-zA-Z0-9\._-])*@([a-zA-Z0-9_-])+([a-zA-Z0-9\._-]+)+$/', $_GET['Email']))
{
    $email = $_GET['Email'];
}
if (isset($_GET['key']) && (strlen($_GET['key']) == 32))//The Activation key will always be 32 since it is MD5 Hash
{
    $key = $_GET['key'];
}


if (isset($Email) && isset($key))
{
    // Update the database to set the "activation" field to null

    $query_activate_account = "UPDATE userDB SET activation=NULL WHERE(email ='$Email' AND activation='$key')LIMIT 1";


    $result_activate_account = mysqli_query($db, $query_activate_account) ;

    // Print a customized message:
    if (mysqli_affected_rows($db) == 1)//if update query was successfull
    {
    echo '<div class="success">Your account is now active. You may now <a href="login.php">Log in</a></div>';

    } else
    {
        echo '<div class="errormsgbox">Oops !Your account could not be activated. Please recheck the link or contact the system administrator.</div>';

    }

    mysqli_close($db);

} else {
        echo '<div class="errormsgbox">Error Occured .</div>';
}


?>

If any more information is requested I will edit this post.

Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
still2blue
  • 193
  • 1
  • 18
  • 1
    If the browser gets a blank page, this might help: http://stackoverflow.com/questions/1475297/phps-white-screen-of-death – Mike Nov 08 '15 at 21:08
  • In `$query_verify_email = "SELECT * FROM userDB WHERE email ='$Email'"; $result_verify_email = mysqli_query($db, $query_verify_email); if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false) $_SESSION['errormessage'] = "Sorry, that email address has already been registered!
    If you already have an account, login below.

    "; header("Location: index.php"); }` shouldn't `if (!$result_verify_email)` be `if ($result_verify_email)`? You want to execute the `if` if the query *succeeds* ie. if the email is *found.*
    – Darwin von Corax Nov 08 '15 at 21:16
  • 3
    Your code is *wide open* to **SQL injection attacks**. Users can pretty much execute any code they want on your database. Also, you're **storing user passwords in *plain text***. This is **grossly irresponsible** to your users. Passwords should be obscured with a 1-way hash and should *never* be retrievable, not even by you as the database administrator. – David Nov 08 '15 at 21:17
  • You have a lot of disgraceful errors, honestly. I'd suggest you turn on `display_errors` or start inspecting your error log. You use `isset($Email) && isset($key)` but the variable is `$email`, so clearly this will never be true. Remember variables are case sensitive. And yes, you are vulnerable to SQL injection, Email header injection, not to mention your error message at the top might never be visible in your browser because you have it above the html tags (some browsers may ignore this). There's just too much fail here. Please debug more - closing as too broad. – Sherif Nov 08 '15 at 21:24

1 Answers1

1
 $query_verify_email = "SELECT * FROM userDB WHERE email ='$Email'";
 $result_verify_email = mysqli_query($db, $query_verify_email);
 if (!$result_verify_email) {//if the Query Failed ,similar to if($result_verify_email==false)
      $_SESSION['errormessage'] = "Sorry, that email address has already been registered!<br />If you already have an account, login below.<br /><br />";
      header("Location: index.php");
 }

http://php.net/manual/en/mysqli.query.php

Returns FALSE on failure. For successful SELECT, SHOW, DESCRIBE or EXPLAIN queries mysqli_query() will return a mysqli_result object. For other successful queries mysqli_query() will return TRUE.

Since you are using a correct SQL select statement, mysqli_query will return a mysqli_result object.

There is a num_rows attribute in mysqli_result that indicates the number of rows found. You can use it to check if there is a record with that email.
Always use LIMIT 1 when you expect 1 result.

FIX:

$query_verify_email = "SELECT * FROM userDB WHERE email ='$Email' LIMIT 1";
$result_verify_email = mysqli_query($mysqli, $query_verify_email);

if (is_object($result_verify_email) && $result_verify_email->num_rows > 0) {
    echo "Email already exists";
} 
Nisse Engström
  • 4,738
  • 23
  • 27
  • 42
Velko Georgiev
  • 684
  • 4
  • 11