PHP Developers Network

A community of PHP developers offering assistance, advice, discussion, and friendship.
 
Loading
It is currently Sun Oct 22, 2017 3:53 pm

All times are UTC - 5 hours




Post new topic Reply to topic  [ 10 posts ] 
Author Message
PostPosted: Thu Sep 14, 2017 7:10 pm 
Offline
Forum Contributor

Joined: Wed Jan 18, 2017 4:43 pm
Posts: 171
Programmers,

I wrote a registration.php (member reg) and it was working fine but the coding was not perfect (old version).
Neated-up the new version but I see a complete blank page once I click "Register" button. I do not get this mssg any more:

Thank you for your registration! Check your email for details on how to activate your account which you just registered."

What is wrong ?

Old version:

Syntax: [ Download ] [ Hide ]
<?php

/*
ERROR HANDLING
*/

declare(strict_types=1);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

include 'config.php';

// check if user is already logged in
if (is_logged() === true) {
        die("You are already logged-in! No need to register again!");
}

if ($_SERVER['REQUEST_METHOD'] == "POST")
{
        if (isset($_POST["username"]) &&
           isset($_POST["password"]) &&
           isset($_POST["password_confirmation"]) &&
           isset($_POST["email"]) &&
           isset($_POST["email_confirmation"]) &&
           isset($_POST["first_name"]) &&
           isset($_POST["gender"]) &&
           isset($_POST["surname"])) {
 
                //TypeCast the INT to STRING on the 1st parameter of sha1 as 1st parameter needs to be a STRING.
                $account_activation_code = sha1( (string) mt_rand(5, 30));
                $account_activation_link = "http://www.".$site_domain."/".$social_network_name."/activate_account.php?email=".$_POST['email']."&account_activation_code=".$account_activation_code."";
                $username       = trim(mysqli_real_escape_string($conn, $_POST["username"]));
                $password       = $_POST["password"];
                $password_confirmation  = $_POST["password_confirmation"];
        $first_name     = trim(mysqli_real_escape_string($conn, $_POST["first_name"]));
        $surname        = trim(mysqli_real_escape_string($conn, $_POST["surname"]));
                $gender         = trim(mysqli_real_escape_string($conn, $_POST["gender"]));
        $email          = trim($_POST["email"]);
        $email_confirmation = trim($_POST["email_confirmation"]);
        $account_activation_status = 0; // 1 = active | 0 = not active

        //Hashed Password.
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
       
                //SEE IF BELOW CODE AFTER FOLLOWING WORKS OR NOT AS SUBSTITUTE FUNCTION OVER mysqli_stmt_get_result FUNCTION
                //Select Username and Email to check against Mysql DB if they are already registered or not.
                $stmt = mysqli_prepare($conn, "SELECT usernames, emails FROM users WHERE usernames = ? OR emails = ?");
                mysqli_stmt_bind_param($stmt, 'ss', $username, $email_confirmation);
                mysqli_stmt_execute($stmt);
                $result = mysqli_stmt_get_result($stmt);
               
                $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
       
                // Check if inputted Username is already registered or not.
                if ($row['usernames'] == $username) {
                        $_SESSION['error'] = "That username is already registered.";
                // Check if inputted Username is between 8 to 30 characters long or not.
                } elseif (strlen($username) < 8 || strlen($username) > 30) {
                        $_SESSION['error'] = "Username must be between 8 to 30 characters long!";
                // Check if inputted Email is already registered or not.
                } elseif ($row['emails'] == $email) {
                        $_SESSION['error'] = "That email is already registered.";
                // Check if both inputted EMails match or not.
                } elseif ($email != $email_confirmation) {
                        $_SESSION['error'] = "Emails don't match!";
                // Check if inputed Email is valid or not.
                } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                        $_SESSION['error'] = "Invalid email! Insert your real Email in order for us to email you your account activation details.";
                // Check if both inputted Passwords match or not.
                } elseif ($password != $password_confirmation) {
                        $_SESSION['error'] = "Passwords don't match.";
                // Check if Password is between 8 to 30 characters long or not.
                } elseif (strlen($password) < 8 || strlen($password) > 30) {
                        $_SESSION['error'] = "Password must be between 6 to 30 characters long!";
                } else {

                        //Insert the user's input into Mysql database using php's sql injection prevention method.
                        $stmt = mysqli_prepare($conn, "INSERT INTO users(usernames, passwords, emails, first_names, surnames, genders, accounts_activations_codes, accounts_activations) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                        mysqli_stmt_bind_param($stmt, 'sssssssi', $username, $hashed_password, $email, $first_name, $surname, $gender, $account_activation_code, $account_activation_status);
                        mysqli_stmt_execute($stmt);

                        //Check if user's registration data was successful submitted or not.
                        if (mysqli_stmt_insert_id($stmt)) {
                                echo "<h3 style='text-align:center'>Thank you for your registration!<br /> Check your email for details on how to activate your account you just registered.</h3>";

                                //Send account activation link by email for user to confirm his email and activate his new account.
                                $to = $email;
                                $subject = "Your ".$site_name." account activation!";
                                $body  = nl2br("
                                ===============================\r\n
                                "
.$site_name." \r\n
                                ===============================\r\n
                                From: "
.$site_admin_email."\r\n
                                To: "
.$email."\r\n
                                Subject: Yours "
.$subject." account activation \r\n
                                Message: "
.$first_name." ".$surname."\r\n You need to click on following <a href=".$account_activation_link.">link</a> to activate your account by confirming your email address. \r\n");
                                $headers = "From: " . $site_admin_email . "\r\n";
                       
                            if (mail($to,$subject,$body,$headers)) {
                                $_SESSION['error'] = "Registration sucessful! Check your email for further instructions!";
                                       
                                        //Clear the Session Error so it can no longer be used.
                                        unset($_SESSION['error']);
                                        unset($_POST);
                                        exit();
                                       
                                        //Redirect user to login page after 5 seconds.
                                        header("refresh:5;url=login.php");
                            }
                                else
                                {
                                $_SESSION['error'] = "Email not sent, please contact website administrator!";
                            }                      
                        }
                        else
                        {
                                $_SESSION['error'] = "There was a problem in trying to register you! Try again some other time.";
                        }
            }
        }
}

?>
<!DOCTYPE html>
<html>
        <head>
                <title><?php $social_network_name ?> Signup Page</title>
        </head>
<body>
<div class ="container">

<?php

// error messages
if (isset($_SESSION['error']) && !empty($_SESSION['error'])) {
        echo '<p style="color:red;">'.$_SESSION['error'].'</p>';
}

?>

<form method="post" action="">
        <center><h2>Signup Form</h2></center>
        <div class="form-group">
                <center><label>Username:</label>
                <input type="text" placeholder="Enter a unique Username" name="username" required [A-Za-z0-9] value="<?php if(isset($_POST['username'])) { echo htmlentities($_POST['username']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Password:</label>
                <input type="password" placeholder="Enter a new Password" name="password" required [A-Za-z0-9]></center>
        </div>
        <div class="form-group">
                <center><label>Repeat Password:</label>
                <input type="password" placeholder="Repeat a new Password" name="password_confirmation" required [A-Za-z0-9]></center>
        </div>
        <div class="form-group">
                <center><label>First Name:</label>
                <input type="text" placeholder="Enter your First Name" name="first_name" required [A-Za-z] value="<?php if(isset($_POST['first_name'])) { echo htmlentities($_POST['first_name']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Surname:</label>
                <input type="text" placeholder="Enter your Surname" name="surname" required [A-Za-z] value="<?php if(isset($_POST['surname'])) { echo htmlentities($_POST['surname']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Gender:</label>
                <input type="radio" name="gender" value="male" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Male<input type="radio" name="gender" value="female" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Female</center>
        </div>
        <div class="form-group">
                <center><label>Email:</label>
                <input type="email" placeholder="Enter your Email" name="email" required [A-Za-z0-9] value="<?php if(isset($_POST['email'])) { echo htmlentities($_POST['email']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Repeat Email:</label>
                <input type="email" placeholder="Repeat your Email" name="email_confirmation" required [A-Za-z0-9] value="<?php if(isset($_POST['email_confirmation'])) { echo htmlentities($_POST['email_confirmation']); }?>"></center>
        </div>
        <center><button type="submit" class="btn btn-default" name="submit">Register!</button></center>
        <center><font color="red" size="3"><b>Already have an account ?</b><br><a href="login.php">Login here!</a></font></center>

</form>

</div>
</body>
</html>
 


New Version:

Syntax: [ Download ] [ Hide ]
<?php

/*
ERROR HANDLING
*/

declare(strict_types=1);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

include 'config.php';

// check if user is already logged in
if (is_logged() === true) {
        die("You are already logged-in! No need to register again!");
}

if ($_SERVER['REQUEST_METHOD'] == "POST")
{
        if (isset($_POST["username"]) &&
           isset($_POST["password"]) &&
           isset($_POST["password_confirmation"]) &&
           isset($_POST["email"]) &&
           isset($_POST["email_confirmation"]) &&
           isset($_POST["first_name"]) &&
           isset($_POST["gender"]) &&
           isset($_POST["surname"])) {
 
                //TypeCast the INT to STRING on the 1st parameter of sha1 as 1st parameter needs to be a STRING.
                $account_activation_code = sha1( (string) mt_rand(5, 30));
                $account_activation_link = "http://www.".$site_domain."/".$social_network_name."/activate_account.php?email=".$_POST['email']."&account_activation_code=".$account_activation_code."";
                $username       = trim(mysqli_real_escape_string($conn, $_POST["username"]));
                $password       = $_POST["password"];
                $password_confirmation  = $_POST["password_confirmation"];
        $first_name     = trim(mysqli_real_escape_string($conn, $_POST["first_name"]));
        $surname        = trim(mysqli_real_escape_string($conn, $_POST["surname"]));
                $gender         = trim(mysqli_real_escape_string($conn, $_POST["gender"]));
        $email          = trim($_POST["email"]);
        $email_confirmation = trim($_POST["email_confirmation"]);
        $account_activation_status = 0; // 1 = active | 0 = not active

        //Hashed Password.
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
       
                //SEE IF BELOW CODE AFTER FOLLOWING WORKS OR NOT AS SUBSTITUTE FUNCTION OVER mysqli_stmt_get_result FUNCTION
                //Select Username and Email to check against Mysql DB if they are already registered or not.
                $stmt = mysqli_prepare($conn, "SELECT usernames, emails FROM users WHERE usernames = ? OR emails = ?");
                mysqli_stmt_bind_param($stmt, 'ss', $username, $email_confirmation);
                mysqli_stmt_execute($stmt);
                $result = mysqli_stmt_get_result($stmt);
               
                $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
       
                // Check if inputted Username is already registered or not.
                if ($row['usernames'] == $username) {
                        $_SESSION['error'] = "That username is already registered.";
                // Check if inputted Username is between 8 to 30 characters long or not.
                } elseif (strlen($username) < 8 || strlen($username) > 30) {
                        $_SESSION['error'] = "Username must be between 8 to 30 characters long!";
                // Check if inputted Email is already registered or not.
                } elseif ($row['emails'] == $email) {
                        $_SESSION['error'] = "That email is already registered.";
                // Check if both inputted EMails match or not.
                } elseif ($email != $email_confirmation) {
                        $_SESSION['error'] = "Emails don't match!";
                // Check if inputed Email is valid or not.
                } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                        $_SESSION['error'] = "Invalid email! Insert your real Email in order for us to email you your account activation details.";
                // Check if both inputted Passwords match or not.
                } elseif ($password != $password_confirmation) {
                        $_SESSION['error'] = "Passwords don't match.";
                // Check if Password is between 8 to 30 characters long or not.
                } elseif (strlen($password) < 8 || strlen($password) > 30) {
                        $_SESSION['error'] = "Password must be between 6 to 30 characters long!";
                } else {

                        //Insert the user's input into Mysql database using php's sql injection prevention method.
                        $stmt = mysqli_prepare($conn, "INSERT INTO users(usernames, passwords, emails, first_names, surnames, genders, accounts_activations_codes, accounts_activations) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                        mysqli_stmt_bind_param($stmt, 'sssssssi', $username, $hashed_password, $email, $first_name, $surname, $gender, $account_activation_code, $account_activation_status);
                        mysqli_stmt_execute($stmt);

                        //Check if user's registration data was successful submitted or not.
                        if (mysqli_stmt_insert_id($stmt)) {
                                echo "<h3 style='text-align:center'>Thank you for your registration!<br /> Check your email for details on how to activate your account you just registered.</h3>";

                                //Send account activation link by email for user to confirm his email and activate his new account.
                                $to = $email;
                                $subject = "Your ".$site_name." account activation!";
                                $body  = nl2br("
                                ===============================\r\n
                                "
.$site_name." \r\n
                                ===============================\r\n
                                From: "
.$site_admin_email."\r\n
                                To: "
.$email."\r\n
                                Subject: Yours "
.$subject." account activation \r\n
                                Message: "
.$first_name." ".$surname."\r\n You need to click on following <a href=".$account_activation_link.">link</a> to activate your account by confirming your email address. \r\n");
                                $headers = "From: " . $site_admin_email . "\r\n";
                       
                            if (mail($to,$subject,$body,$headers)) {
                                $_SESSION['error'] = "Registration sucessful! Check your email for further instructions!";
                                       
                                        //Clear the Session Error so it can no longer be used.
                                        unset($_SESSION['error']);
                                        unset($_POST);
                                        exit();
                                       
                                        //Redirect user to login page after 5 seconds.
                                        header("refresh:5;url=login.php");
                            }
                                else
                                {
                                $_SESSION['error'] = "Email not sent, please contact website administrator!";
                            }                      
                        }
                        else
                        {
                                $_SESSION['error'] = "There was a problem in trying to register you! Try again some other time.";
                        }
            }
        }
}

?>
<!DOCTYPE html>
<html>
        <head>
                <title><?php $social_network_name ?> Signup Page</title>
        </head>
<body>
<div class ="container">

<?php

// error messages
if (isset($_SESSION['error']) && !empty($_SESSION['error'])) {
        echo '<p style="color:red;">'.$_SESSION['error'].'</p>';
}

?>

<form method="post" action="">
        <center><h2>Signup Form</h2></center>
        <div class="form-group">
                <center><label>Username:</label>
                <input type="text" placeholder="Enter a unique Username" name="username" required [A-Za-z0-9] value="<?php if(isset($_POST['username'])) { echo htmlentities($_POST['username']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Password:</label>
                <input type="password" placeholder="Enter a new Password" name="password" required [A-Za-z0-9]></center>
        </div>
        <div class="form-group">
                <center><label>Repeat Password:</label>
                <input type="password" placeholder="Repeat a new Password" name="password_confirmation" required [A-Za-z0-9]></center>
        </div>
        <div class="form-group">
                <center><label>First Name:</label>
                <input type="text" placeholder="Enter your First Name" name="first_name" required [A-Za-z] value="<?php if(isset($_POST['first_name'])) { echo htmlentities($_POST['first_name']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Surname:</label>
                <input type="text" placeholder="Enter your Surname" name="surname" required [A-Za-z] value="<?php if(isset($_POST['surname'])) { echo htmlentities($_POST['surname']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Gender:</label>
                <input type="radio" name="gender" value="male" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Male<input type="radio" name="gender" value="female" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Female</center>
        </div>
        <div class="form-group">
                <center><label>Email:</label>
                <input type="email" placeholder="Enter your Email" name="email" required [A-Za-z0-9] value="<?php if(isset($_POST['email'])) { echo htmlentities($_POST['email']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Repeat Email:</label>
                <input type="email" placeholder="Repeat your Email" name="email_confirmation" required [A-Za-z0-9] value="<?php if(isset($_POST['email_confirmation'])) { echo htmlentities($_POST['email_confirmation']); }?>"></center>
        </div>
        <center><button type="submit" class="btn btn-default" name="submit">Register!</button></center>
        <center><font color="red" size="3"><b>Already have an account ?</b><br><a href="login.php">Login here!</a></font></center>

</form>

</div>
</body>
</html>
 


What is wrong with the new version ?


Top
 Profile  
 
PostPosted: Thu Sep 14, 2017 8:34 pm 
Offline
Moderator
User avatar

Joined: Tue Nov 09, 2010 3:39 pm
Posts: 6391
Location: Montreal, Canada
There's plenty wrong with it. Is there a specific problem you're trying to resolve?

_________________
Supported PHP versions No longer supported versions


Top
 Profile  
 
PostPosted: Fri Sep 15, 2017 5:18 am 
Offline
Forum Contributor

Joined: Wed Jan 18, 2017 4:43 pm
Posts: 171
Thank you Celeraun for trying to help.
When I click the REGISTER button, I see a blank page instead of the ECHO:
"Thank you for your registration! Check your email for details on how to activate your account which you just registered".
Anyway, I'd appreciate it if you point-out what plenty of things are wrong on both versions.


Top
 Profile  
 
PostPosted: Fri Sep 15, 2017 6:02 am 
Offline
Moderator
User avatar

Joined: Tue Nov 09, 2010 3:39 pm
Posts: 6391
Location: Montreal, Canada
Code review? Okie dokie.

Syntax: [ Download ] [ Hide ]
<?php

/*
ERROR HANDLING
*/


/**
 * I don't see why you need this here
 * This is also potentially the cause of your blank page
 */

declare(strict_types=1);
/**
 * This belongs in your php.ini
 */

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

/**
 * What? No. Use autoloading
 */

include 'config.php';

// check if user is already logged in
/**
 * You should try to avoid writing global functions
 */

if (is_logged() === true) {
    /**
     * die() is not appropriate error handling. Redirect the user to a proper error page.
     * Make sure you use appropriate HTTP response codes
     */

        die("You are already logged-in! No need to register again!");
}

/**
 * You're mixing presentation and logic. Don't do that.
 * Logic goes in the models, presentation goes in the views
 */

if ($_SERVER['REQUEST_METHOD'] == "POST")
{
    /** Fix your indentation, it's all over the place **/

    /**
     * Extract this to a method to keep things easier to read
     */

        if (isset($_POST["username"]) &&
           isset($_POST["password"]) &&
           isset($_POST["password_confirmation"]) &&
           isset($_POST["email"]) &&
           isset($_POST["email_confirmation"]) &&
           isset($_POST["first_name"]) &&
           isset($_POST["gender"]) &&
           isset($_POST["surname"])) {
 
                //TypeCast the INT to STRING on the 1st parameter of sha1 as 1st parameter needs to be a STRING.
                $account_activation_code = sha1( (string) mt_rand(5, 30));
                $account_activation_link = "http://www.".$site_domain."/".$social_network_name."/activate_account.php?email=".$_POST['email']."&account_activation_code=".$account_activation_code."";
                /**
                 * mysqli_real_escape_string is not needed for prepared statements
                 * You should prefer PDO to mysqli as it's far easier to use
                 */

                $username       = trim(mysqli_real_escape_string($conn, $_POST["username"]));
                $password       = $_POST["password"];
                $password_confirmation  = $_POST["password_confirmation"];
                /**
                 * If you're going to call trim on everything in the array, consider using array_map
                 */

        $first_name     = trim(mysqli_real_escape_string($conn, $_POST["first_name"]));
        $surname        = trim(mysqli_real_escape_string($conn, $_POST["surname"]));
                $gender         = trim(mysqli_real_escape_string($conn, $_POST["gender"]));
        $email          = trim($_POST["email"]);
        $email_confirmation = trim($_POST["email_confirmation"]);
        $account_activation_status = 0; // 1 = active | 0 = not active

        //Hashed Password.
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
       
                //SEE IF BELOW CODE AFTER FOLLOWING WORKS OR NOT AS SUBSTITUTE FUNCTION OVER mysqli_stmt_get_result FUNCTION
                //Select Username and Email to check against Mysql DB if they are already registered or not.
                $stmt = mysqli_prepare($conn, "SELECT usernames, emails FROM users WHERE usernames = ? OR emails = ?");
                mysqli_stmt_bind_param($stmt, 'ss', $username, $email_confirmation);
                mysqli_stmt_execute($stmt);
                $result = mysqli_stmt_get_result($stmt);

                /**
                 * What if the query fails and $result is false?
                 */
             
                $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
       
                // Check if inputted Username is already registered or not.
                if ($row['usernames'] == $username) {
                        $_SESSION['error'] = "That username is already registered.";
                // Check if inputted Username is between 8 to 30 characters long or not.
                /**
                 * Why else? What if there are multiple problems with the registration?
                 */

                } elseif (strlen($username) < 8 || strlen($username) > 30) {
                        $_SESSION['error'] = "Username must be between 8 to 30 characters long!";
                // Check if inputted Email is already registered or not.
                } elseif ($row['emails'] == $email) {
                        $_SESSION['error'] = "That email is already registered.";
                // Check if both inputted EMails match or not.
                } elseif ($email != $email_confirmation) {
                        $_SESSION['error'] = "Emails don't match!";
                // Check if inputed Email is valid or not.
                } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                        $_SESSION['error'] = "Invalid email! Insert your real Email in order for us to email you your account activation details.";
                // Check if both inputted Passwords match or not.
                } elseif ($password != $password_confirmation) {
                        $_SESSION['error'] = "Passwords don't match.";
                // Check if Password is between 8 to 30 characters long or not.
                /**
                 * This is an unnecessary restriction that can only serve to make passwords weaker
                 */

                } elseif (strlen($password) < 8 || strlen($password) > 30) {
                        $_SESSION['error'] = "Password must be between 6 to 30 characters long!";
                } else {

                        //Insert the user's input into Mysql database using php's sql injection prevention method.
                        $stmt = mysqli_prepare($conn, "INSERT INTO users(usernames, passwords, emails, first_names, surnames, genders, accounts_activations_codes, accounts_activations) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                        mysqli_stmt_bind_param($stmt, 'sssssssi', $username, $hashed_password, $email, $first_name, $surname, $gender, $account_activation_code, $account_activation_status);
                        mysqli_stmt_execute($stmt);

                        //Check if user's registration data was successful submitted or not.
                        if (mysqli_stmt_insert_id($stmt)) {
                            /**
                             * Don't echo HTML. Separate your concerns
                             */

                                echo "<h3 style='text-align:center'>Thank you for your registration!<br /> Check your email for details on how to activate your account you just registered.</h3>";

                                //Send account activation link by email for user to confirm his email and activate his new account.
                                /**
                                 * Abstract this out into its own method, remove it from the view
                                 */

                                $to = $email;
                                $subject = "Your ".$site_name." account activation!";
                                $body  = nl2br("
                                ===============================\r\n
                                "
.$site_name." \r\n
                                ===============================\r\n
                                From: "
.$site_admin_email."\r\n
                                To: "
.$email."\r\n
                                Subject: Yours "
.$subject." account activation \r\n
                                Message: "
.$first_name." ".$surname."\r\n You need to click on following <a href=".$account_activation_link.">link</a> to activate your account by confirming your email address. \r\n");
                                $headers = "From: " . $site_admin_email . "\r\n";
                       
                            if (mail($to,$subject,$body,$headers)) {
                                $_SESSION['error'] = "Registration sucessful! Check your email for further instructions!";
                                       
                                        //Clear the Session Error so it can no longer be used.
                                        unset($_SESSION['error']);
                                        unset($_POST);
                                        exit();
                                       
                                        //Redirect user to login page after 5 seconds.
                                        header("refresh:5;url=login.php");
                            }
                                else
                                {
                                $_SESSION['error'] = "Email not sent, please contact website administrator!";
                            }                      
                        }
                        else
                        {
                                $_SESSION['error'] = "There was a problem in trying to register you! Try again some other time.";
                        }
            }
        }
}

?>
<!DOCTYPE html>
<html>
        <head>
                <title><?php /** echo? **/$social_network_name ?> Signup Page</title>
        </head>
<body>
<div class ="container">

<?php

// error messages
if (isset($_SESSION['error']) && !empty($_SESSION['error'])) {
    /**
     * Don't echo HTML. Use alternate if/else format
     */

        echo '<p style="color:red;">'.$_SESSION['error'].'</p>';
}

?>

<form method="post" action="">
        <center><h2>Signup Form</h2></center>
        <div class="form-group">
                <center><label>Username:</label>
                    <!-- You have validation in the HTML that isn't repeated on the server -->
                <input type="text" placeholder="Enter a unique Username" name="username" required [A-Za-z0-9] value="<?php if(isset($_POST['username'])) { echo htmlentities($_POST['username']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Password:</label>
                <input type="password" placeholder="Enter a new Password" name="password" required [A-Za-z0-9]></center>
        </div>
        <div class="form-group">
                <center><label>Repeat Password:</label>
                <input type="password" placeholder="Repeat a new Password" name="password_confirmation" required [A-Za-z0-9]></center>
        </div>
        <div class="form-group">
                <center><label>First Name:</label>
                <input type="text" placeholder="Enter your First Name" name="first_name" required [A-Za-z] value="<?php if(isset($_POST['first_name'])) { echo htmlentities($_POST['first_name']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Surname:</label>
                <input type="text" placeholder="Enter your Surname" name="surname" required [A-Za-z] value="<?php if(isset($_POST['surname'])) { echo htmlentities($_POST['surname']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Gender:</label>
                <input type="radio" name="gender" value="male" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Male<input type="radio" name="gender" value="female" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Female</center>
        </div>
        <div class="form-group">
                <center><label>Email:</label>
                <input type="email" placeholder="Enter your Email" name="email" required [A-Za-z0-9] value="<?php if(isset($_POST['email'])) { echo htmlentities($_POST['email']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Repeat Email:</label>
                <input type="email" placeholder="Repeat your Email" name="email_confirmation" required [A-Za-z0-9] value="<?php if(isset($_POST['email_confirmation'])) { echo htmlentities($_POST['email_confirmation']); }?>"></center>
        </div>
        <center><button type="submit" class="btn btn-default" name="submit">Register!</button></center>
        <center><font color="red" size="3"><b>Already have an account ?</b><br><a href="login.php">Login here!</a></font></center>

</form>

</div>
</body>
</html>

_________________
Supported PHP versions No longer supported versions


Top
 Profile  
 
PostPosted: Fri Sep 15, 2017 5:18 pm 
Offline
Forum Contributor

Joined: Wed Jan 18, 2017 4:43 pm
Posts: 171
Thank you very much for spending your time and energy reviewing my code.
On my original post, I gave 2 versions of my registration.php.
Old version had mysqli_real_escape_string but the new version did not as programmers told me it is not needed with prep stmts.

It seems you reviewed my old version.
1. You mention:

Syntax: [ Download ] [ Hide ]
<span style="font-weight: bold">"ERROR HANDLING
*/

/**
 * I don&#39;t see why you need this here
 * This is also potentially the cause of your blank page
 */
declare&#40;strict_types=1&#41;;
/**
 * This belongs in your php.ini"
</span>


No. The old version is not showing the blank page. Old version working fine. It is the new version showing the blank page.
On new version, I replaced "Exit();" with "clear_registration_session();" and that is when the blank page issue started. Kindly review new version mentioned on my original post, when you get the time.
That function looks like this from lines 147-157.

Syntax: [ Download ] [ Hide ]
<span style="font-weight: bold"><?php
//Clear Registration Session.
function clear_registration_session&#40;&#41;
        {
                //Clear the User Form inputs, Session Messages and Session Errors so they can no longer be used.
                unset&#40;$_SESSION[&#39;message&#39;]&#41;;
                unset&#40;$_SESSION[&#39;error&#39;]&#41;;
                unset&#40;$_POST&#41;;
                exit&#40;&#41;;
        }
?></span>



2. You mention:

Syntax: [ Download ] [ Hide ]
/**
 * What? No. Use autoloading
 */

include &#39;config.php&#39;;


Care to elaborate more by giving a sample snippet so I understand you better ?


3. You mention:

Syntax: [ Download ] [ Hide ]
<span style="font-weight: bold">// check if user is already logged in
/**
 * You should try to avoid writing global functions
 */

if &#40;is_logged&#40;&#41; === true&#41; {
   /**
     * die&#40;&#41; is not appropriate error handling. Redirect the user to a proper error page.
     * Make sure you use appropriate HTTP response codes
     */

        die&#40;"You are already logged-in! No need to register again!"&#41;;
}

/**
 * You&#39;re mixing presentation and logic. Don&#39;t do that.
 * Logic goes in the models, presentation goes in the views
 */
</span>


Care to give the error handling (along with proper http responses) you deem appropriate ?
This will be a good learning curve for us newbies!


4. You mention:
Syntax: [ Download ] [ Hide ]
<span style="font-weight: bold">" * If you&#39;re going to call trim on everything in the array, consider using array_map
                 */
"
</span>


I have never heard of array map before. Must research on it. In the meanwhile I'd appreciate any code snippets from you on this array map.


5. You mention:
Syntax: [ Download ] [ Hide ]
<span style="font-weight: bold">"/**
                 * What if the query fails and $result is false?
                 */        
"
</span>


I actually fixed this on the new version that is showing the blank page.
Do you mind checking the new version to see if I got it right ?


6. You mention:
Syntax: [ Download ] [ Hide ]
<span style="font-weight: bold">"/**
                 * Why else? What if there are multiple problems with the registration?
                 */
"
</span>


Actually, another programmer added these when he edited my script. He is no longer available. I will ponder more about this.


7.
You mention:
Syntax: [ Download ] [ Hide ]
<span style="font-weight: bold">" * This is an unnecessary restriction that can only serve to make passwords weaker
                 */
                } elseif &#40;strlen&#40;$password&#41; < 8 || strlen&#40;$password&#41; > 30&#41; {
                        $_SESSION[&#39;error&#39;] = "
Password must be between 6 to 30 characters long!";
                } else {
"
</span>


Mmm. Usually reg pages ask for this and so I just copied them. Curious, what would you do here ?


8.
You mention:
Syntax: [ Download ] [ Hide ]
"
//Check if user&#39;s registration data was successful submitted or not.
                        if &#40;mysqli_stmt_insert_id&#40;$stmt&#41;&#41; {
                            /**
                             * Don&#39;t echo HTML. Separate your concerns
                             */
                                echo "
<h3 style=&#39;text-align:center&#39;>Thank you for your registration!<br /> Check your email for details on how to activate your account you just registered.</h3>";
"


How do you mean ? A sample snippet would indeed make me remember things like this more often.


9.
You mention:
Syntax: [ Download ] [ Hide ]
<span style="font-weight: bold">"
//Send account activation link by email for user to confirm his email and activate his new account.
                                /**
                                 * Abstract this out into its own method, remove it from the view
                                 */
                                $to = $email;
                                $subject = "
Your ".$site_name." account activation!";
                                $body  = nl2br&#40;"

                                ===============================\r\n
                                ".$site_name." \r\n
                                ===============================\r\n
                                From: ".$site_admin_email."\r\n
                                To: ".$email."\r\n
                                Subject: Yours ".$subject." account activation \r\n
                                Message: ".$first_name." ".$surname."\r\n You need to click on following <a href=".$account_activation_link.">link</a> to activate your account by confirming your email address. \r\n"&#41;;
                                $headers = "
From: " . $site_admin_email . "\r\n";
                       
                            if &#40;mail&#40;$to,$subject,$body,$headers&#41;&#41; {
                                $_SESSION[&#39;error&#39;] = "
Registration sucessful! Check your email for further instructions!";
"
</span>


Where should I remove it to ?
10.
You mention:
Syntax: [ Download ] [ Hide ]
<span style="font-weight: bold"><?php

// error messages
if &#40;isset&#40;$_SESSION[&#39;error&#39;]&#41; && !empty&#40;$_SESSION[&#39;error&#39;]&#41;&#41; {
   /**
     * Don&#39;t echo HTML. Use alternate if/else format
     */

        echo &#39;<p style="color:red;">&#39;.$_SESSION[&#39;error&#39;].&#39;</p>&#39;;
}

?></span>


Use like what ? A snippet of code would make things clear to us new students.


Thank you very much for your time reading this.
I hope you review my new version and make changes with code snippets wherever you deem things need changing or where code is missing. And then attach your fixes to this thread for future newbies to download and learn from.

PS - I am uploading (if possible) both the new and old versions of the script. That way, indentations would be intact.
EDIT: It is not allowing me to upload .php or .txt files.


Thanks


Top
 Profile  
 
PostPosted: Sat Sep 16, 2017 5:27 am 
Offline
Moderator
User avatar

Joined: Tue Nov 09, 2010 3:39 pm
Posts: 6391
Location: Montreal, Canada
UniqueIdeaMan wrote:
Thank you very much for spending your time and energy reviewing my code.
On my original post, I gave 2 versions of my registration.php.
Old version had mysqli_real_escape_string but the new version did not as programmers told me it is not needed with prep stmts.

It seems you reviewed my old version.

UniqueIdeaMan wrote:
...

New Version:

Syntax: [ Download ] [ Hide ]
<?php

/*
ERROR HANDLING
*/

declare(strict_types=1);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

include 'config.php';

// check if user is already logged in
if (is_logged() === true) {
        die("You are already logged-in! No need to register again!");
}

if ($_SERVER['REQUEST_METHOD'] == "POST")
{
        if (isset($_POST["username"]) &&
           isset($_POST["password"]) &&
           isset($_POST["password_confirmation"]) &&
           isset($_POST["email"]) &&
           isset($_POST["email_confirmation"]) &&
           isset($_POST["first_name"]) &&
           isset($_POST["gender"]) &&
           isset($_POST["surname"])) {
 
                //TypeCast the INT to STRING on the 1st parameter of sha1 as 1st parameter needs to be a STRING.
                $account_activation_code = sha1( (string) mt_rand(5, 30));
                $account_activation_link = "http://www.".$site_domain."/".$social_network_name."/activate_account.php?email=".$_POST['email']."&account_activation_code=".$account_activation_code."";
                $username       = trim(mysqli_real_escape_string($conn, $_POST["username"]));
                $password       = $_POST["password"];
                $password_confirmation  = $_POST["password_confirmation"];
        $first_name     = trim(mysqli_real_escape_string($conn, $_POST["first_name"]));
        $surname        = trim(mysqli_real_escape_string($conn, $_POST["surname"]));
                $gender         = trim(mysqli_real_escape_string($conn, $_POST["gender"]));
        $email          = trim($_POST["email"]);
        $email_confirmation = trim($_POST["email_confirmation"]);
        $account_activation_status = 0; // 1 = active | 0 = not active

        //Hashed Password.
                $hashed_password = password_hash($password, PASSWORD_DEFAULT);
       
                //SEE IF BELOW CODE AFTER FOLLOWING WORKS OR NOT AS SUBSTITUTE FUNCTION OVER mysqli_stmt_get_result FUNCTION
                //Select Username and Email to check against Mysql DB if they are already registered or not.
                $stmt = mysqli_prepare($conn, "SELECT usernames, emails FROM users WHERE usernames = ? OR emails = ?");
                mysqli_stmt_bind_param($stmt, 'ss', $username, $email_confirmation);
                mysqli_stmt_execute($stmt);
                $result = mysqli_stmt_get_result($stmt);
               
                $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
       
                // Check if inputted Username is already registered or not.
                if ($row['usernames'] == $username) {
                        $_SESSION['error'] = "That username is already registered.";
                // Check if inputted Username is between 8 to 30 characters long or not.
                } elseif (strlen($username) < 8 || strlen($username) > 30) {
                        $_SESSION['error'] = "Username must be between 8 to 30 characters long!";
                // Check if inputted Email is already registered or not.
                } elseif ($row['emails'] == $email) {
                        $_SESSION['error'] = "That email is already registered.";
                // Check if both inputted EMails match or not.
                } elseif ($email != $email_confirmation) {
                        $_SESSION['error'] = "Emails don't match!";
                // Check if inputed Email is valid or not.
                } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                        $_SESSION['error'] = "Invalid email! Insert your real Email in order for us to email you your account activation details.";
                // Check if both inputted Passwords match or not.
                } elseif ($password != $password_confirmation) {
                        $_SESSION['error'] = "Passwords don't match.";
                // Check if Password is between 8 to 30 characters long or not.
                } elseif (strlen($password) < 8 || strlen($password) > 30) {
                        $_SESSION['error'] = "Password must be between 6 to 30 characters long!";
                } else {

                        //Insert the user's input into Mysql database using php's sql injection prevention method.
                        $stmt = mysqli_prepare($conn, "INSERT INTO users(usernames, passwords, emails, first_names, surnames, genders, accounts_activations_codes, accounts_activations) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                        mysqli_stmt_bind_param($stmt, 'sssssssi', $username, $hashed_password, $email, $first_name, $surname, $gender, $account_activation_code, $account_activation_status);
                        mysqli_stmt_execute($stmt);

                        //Check if user's registration data was successful submitted or not.
                        if (mysqli_stmt_insert_id($stmt)) {
                                echo "<h3 style='text-align:center'>Thank you for your registration!<br /> Check your email for details on how to activate your account you just registered.</h3>";

                                //Send account activation link by email for user to confirm his email and activate his new account.
                                $to = $email;
                                $subject = "Your ".$site_name." account activation!";
                                $body  = nl2br("
                                ===============================\r\n
                                "
.$site_name." \r\n
                                ===============================\r\n
                                From: "
.$site_admin_email."\r\n
                                To: "
.$email."\r\n
                                Subject: Yours "
.$subject." account activation \r\n
                                Message: "
.$first_name." ".$surname."\r\n You need to click on following <a href=".$account_activation_link.">link</a> to activate your account by confirming your email address. \r\n");
                                $headers = "From: " . $site_admin_email . "\r\n";
                       
                            if (mail($to,$subject,$body,$headers)) {
                                $_SESSION['error'] = "Registration sucessful! Check your email for further instructions!";
                                       
                                        //Clear the Session Error so it can no longer be used.
                                        unset($_SESSION['error']);
                                        unset($_POST);
                                        exit();
                                       
                                        //Redirect user to login page after 5 seconds.
                                        header("refresh:5;url=login.php");
                            }
                                else
                                {
                                $_SESSION['error'] = "Email not sent, please contact website administrator!";
                            }                      
                        }
                        else
                        {
                                $_SESSION['error'] = "There was a problem in trying to register you! Try again some other time.";
                        }
            }
        }
}

?>
<!DOCTYPE html>
<html>
        <head>
                <title><?php $social_network_name ?> Signup Page</title>
        </head>
<body>
<div class ="container">

<?php

// error messages
if (isset($_SESSION['error']) && !empty($_SESSION['error'])) {
        echo '<p style="color:red;">'.$_SESSION['error'].'</p>';
}

?>

<form method="post" action="">
        <center><h2>Signup Form</h2></center>
        <div class="form-group">
                <center><label>Username:</label>
                <input type="text" placeholder="Enter a unique Username" name="username" required [A-Za-z0-9] value="<?php if(isset($_POST['username'])) { echo htmlentities($_POST['username']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Password:</label>
                <input type="password" placeholder="Enter a new Password" name="password" required [A-Za-z0-9]></center>
        </div>
        <div class="form-group">
                <center><label>Repeat Password:</label>
                <input type="password" placeholder="Repeat a new Password" name="password_confirmation" required [A-Za-z0-9]></center>
        </div>
        <div class="form-group">
                <center><label>First Name:</label>
                <input type="text" placeholder="Enter your First Name" name="first_name" required [A-Za-z] value="<?php if(isset($_POST['first_name'])) { echo htmlentities($_POST['first_name']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Surname:</label>
                <input type="text" placeholder="Enter your Surname" name="surname" required [A-Za-z] value="<?php if(isset($_POST['surname'])) { echo htmlentities($_POST['surname']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Gender:</label>
                <input type="radio" name="gender" value="male" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Male<input type="radio" name="gender" value="female" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Female</center>
        </div>
        <div class="form-group">
                <center><label>Email:</label>
                <input type="email" placeholder="Enter your Email" name="email" required [A-Za-z0-9] value="<?php if(isset($_POST['email'])) { echo htmlentities($_POST['email']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Repeat Email:</label>
                <input type="email" placeholder="Repeat your Email" name="email_confirmation" required [A-Za-z0-9] value="<?php if(isset($_POST['email_confirmation'])) { echo htmlentities($_POST['email_confirmation']); }?>"></center>
        </div>
        <center><button type="submit" class="btn btn-default" name="submit">Register!</button></center>
        <center><font color="red" size="3"><b>Already have an account ?</b><br><a href="login.php">Login here!</a></font></center>

</form>

</div>
</body>
</html>
 

I reviewed what you posted.

_________________
Supported PHP versions No longer supported versions


Top
 Profile  
 
PostPosted: Sat Sep 16, 2017 5:44 am 
Offline
Moderator
User avatar

Joined: Tue Nov 09, 2010 3:39 pm
Posts: 6391
Location: Montreal, Canada
UniqueIdeaMan wrote:
Kindly review new version mentioned on my original post, when you get the time.

You'll need to post it first.


UniqueIdeaMan wrote:
2. You mention:

Syntax: [ Download ] [ Hide ]
/**
 * What? No. Use autoloading
 */

include 'config.php';


Care to elaborate more by giving a sample snippet so I understand you better ?

http://lmgtfy.com/?q=php+autoloading


UniqueIdeaMan wrote:
3. You mention:

Syntax: [ Download ] [ Hide ]
// check if user is already logged in
/**
 * You should try to avoid writing global functions
 */

if (is_logged() === true) {
    /**
     * die() is not appropriate error handling. Redirect the user to a proper error page.
     * Make sure you use appropriate HTTP response codes
     */

        die("You are already logged-in! No need to register again!");
}

/**
 * You're mixing presentation and logic. Don't do that.
 * Logic goes in the models, presentation goes in the views
 */


Care to give the error handling (along with proper http responses) you deem appropriate ?
This will be a good learning curve for us newbies!

As I said, redirect the user to a suitable page.
https://en.wikipedia.org/wiki/List_of_H ... ent_errors

UniqueIdeaMan wrote:
4. You mention:
Syntax: [ Download ] [ Hide ]
/* If you're going to call trim on everything in the array, consider using array_map
                 */


I have never heard of array map before. Must research on it. In the meanwhile I'd appreciate any code snippets from you on this array map.

http://php.net/manual/en/function.array-map.php


UniqueIdeaMan wrote:
7.
You mention:
Syntax: [ Download ] [ Hide ]
<span style="font-weight: bold">" * This is an unnecessary restriction that can only serve to make passwords weaker
                 */
                } elseif &#40;strlen&#40;$password&#41; < 8 || strlen&#40;$password&#41; > 30&#41; {
                        $_SESSION[&#39;error&#39;] = "
Password must be between 6 to 30 characters long!";
                } else {
"
</span>


Mmm. Usually reg pages ask for this and so I just copied them. Curious, what would you do here ?

What's the benefit to restricting the maximum length? What if I want a 32 character password? Or 128 characters? Why shouldn't I be able to do that? You're essentially forcing me to have a weaker password than I otherwise would without providing any real benefit.


UniqueIdeaMan wrote:
9.
You mention:
Syntax: [ Download ] [ Hide ]
//Send account activation link by email for user to confirm his email and activate his new account.
                                /**
                                 * Abstract this out into its own method, remove it from the view
                                 */

                                $to = $email;
                                $subject = "Your ".$site_name." account activation!";
                                $body  = nl2br("
                                ===============================\r\n
                                "
.$site_name." \r\n
                                ===============================\r\n
                                From: "
.$site_admin_email."\r\n
                                To: "
.$email."\r\n
                                Subject: Yours "
.$subject." account activation \r\n
                                Message: "
.$first_name." ".$surname."\r\n You need to click on following <a href=".$account_activation_link.">link</a> to activate your account by confirming your email address. \r\n");
                                $headers = "From: " . $site_admin_email . "\r\n";
                       
                            if (mail($to,$subject,$body,$headers)) {
                                $_SESSION['error'] = "Registration sucessful! Check your email for further instructions!";
 


Where should I remove it to ?

https://en.wikipedia.org/wiki/Model%E2% ... controller

UniqueIdeaMan wrote:
10.
You mention:
Syntax: [ Download ] [ Hide ]
<?php

// error messages
if (isset($_SESSION['error']) && !empty($_SESSION['error'])) {
    /**
     * Don't echo HTML. Use alternate if/else format
     */

        echo '<p style="color:red;">'.$_SESSION['error'].'</p>';
}

?>

Use like what ? A snippet of code would make things clear to us new students.

http://php.net/manual/en/control-struct ... syntax.php


UniqueIdeaMan wrote:
Thank you very much for your time reading this.
I hope you review my new version and make changes with code snippets wherever you deem things need changing or where code is missing. And then attach your fixes to this thread for future newbies to download and learn from.

I'm happy to review the new version, but you'll have to post it before I can do so. There's no reason you shouldn't be able to post it here, but feel free to use something like pastebin or GitHub.

More importantly, I'll want to see some effort beyond just "show me how" after every comment, otherwise I'm wasting my time. I'm happy to help you learn, I'm not writing your code for you.

_________________
Supported PHP versions No longer supported versions


Top
 Profile  
 
PostPosted: Mon Sep 18, 2017 5:36 pm 
Offline
Forum Contributor

Joined: Wed Jan 18, 2017 4:43 pm
Posts: 171
Celeraun,

If you check my original post, you will see 2 codes. First one is old version and second one is new version.
The new version was showing the blank page. Anyway, that has been sorted.
Your review was on the first bit of code (old version) as you made references to my code lines that exist in the old version and not in the new version.
Anyway, here is the new version again.

Thanks in advance!

Syntax: [ Download ] [ Hide ]
<?php

/*
ERROR HANDLING
*/

declare(strict_types=1);
ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

include 'config.php';

//Step 1: Before registering User account, check if User is already registered or not.

//Check if User is already logged-in or not.
if (is_logged() === true) {
        die("You are already logged-in! No need to register again!");
}

if ($_SERVER['REQUEST_METHOD'] == "POST")
{
//Step 2: Check User Submitted Details.
       
        //Check if user made all the required inputs or not.
        if (isset($_POST["username"]) &&
           isset($_POST["password"]) &&
           isset($_POST["password_confirmation"]) &&
           isset($_POST["email"]) &&
           isset($_POST["email_confirmation"]) &&
           isset($_POST["first_name"]) &&
           isset($_POST["surname"]) &&
           isset($_POST["gender"])) {
                   
//Step  3: Check User details for matches against database. If no matches then validate inputs and register User account.
                   
                //Create variables based on user inputs.
                $username       = trim($_POST["username"]);
                $password       = $_POST["password"];
                $password_confirmation = $_POST["password_confirmation"];
                $email          = trim($_POST["email"]);
        $email_confirmation = trim($_POST["email_confirmation"]);
        $first_name     = trim($_POST["first_name"]);
        $surname        = trim($_POST["surname"]);
                $gender         = $_POST["gender"];    
                $account_activation_code = sha1( (string) mt_rand(5, 30)); //Type Casted the INT to STRING on the 1st parameter of sha1 as it needs to be a STRING.
                $account_activation_link = "http://www.".$site_domain."/".$social_network_name."/activate_account.php?email=".$_POST['email']."&account_activation_code=".$account_activation_code."";
                $account_activation_status = 0; // 1 = active; 0 = not active.
        $hashed_password = password_hash($password, PASSWORD_DEFAULT); //Encrypt the password.
       
                //Select Username and Email to check against Mysql DB if they are already registered or not.
                $stmt = mysqli_prepare($conn, "SELECT usernames, emails FROM users WHERE usernames = ? OR emails = ?");
                mysqli_stmt_bind_param($stmt, 'ss', $username, $email);
                mysqli_stmt_execute($stmt);
                $result = mysqli_stmt_get_result($stmt);               
                $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
       
                // Check if inputted Username is already registered or not.
                if ($row['usernames'] == $username) {
                        $_SESSION['error'] = "That username is already registered.";
                        exit();
                // Check if inputted Username is between the required 8 to 30 characters long or not.
                } elseif (strlen($username) < 8 || strlen($username) > 30) {
                        $_SESSION['error'] = "Username must be between 8 to 30 characters long!";
                        exit();
                // Check if both inputted Emails match or not.
                } elseif ($email != $email_confirmation) {
                        $_SESSION['error'] = "Emails don't match!";
                        exit();
                // Check if inputed Email is valid or not.
                } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                        $_SESSION['error'] = "Invalid email! Insert your real Email in order for us to email you your account activation details.";
                        exit();
                // Check if inputted Email is already registered or not.
                } elseif ($row['emails'] == $email) {
                        $_SESSION['error'] = "That email is already registered.";
                        exit();
                // Check if both inputted Passwords match or not.
                } elseif ($password != $password_confirmation) {
                        $_SESSION['error'] = "Passwords don't match.";
                        exit();
                // Check if Password is between 8 to 30 characters long or not.
                } elseif (strlen($password) < 8 || strlen($password) > 30) {
                        $_SESSION['error'] = "Password must be between 6 to 30 characters long!";
                        exit();
                }
                else
                {
                        //Insert the user's inputs into Mysql database using php's sql injection prevention method "Prepared Statements".
                        $stmt = mysqli_prepare($conn, "INSERT INTO users(usernames, passwords, emails, first_names, surnames, genders, accounts_activations_codes, accounts_activations_statuses) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                        mysqli_stmt_bind_param($stmt, 'sssssssi', $username, $hashed_password, $email, $first_name, $surname, $gender, $account_activation_code, $account_activation_status);
                        mysqli_stmt_execute($stmt);
                        echo "INSERTING";

                        //Check if user's registration data was successfully submitted or not.
                        if (!$stmt)
                        {
                                $_SESSION['error'] = "Sorry! Our system is currently experiencing a problem registering your account! You may try registering some other time.";
                                exit();
                        }
                        else
                        {
                                //Email the account activation link for user to click it to confirm their email and activate their new account.
                                $to = $email;
                                $subject = "Your ".$site_name." account activation details!";
                                $body  = nl2br("
                                ===============================\r\n
                                "
.$site_name." \r\n
                                ===============================\r\n
                                From: "
.$site_admin_email."\r\n
                                To: "
.$email."\r\n
                                Subject: Yours "
.$subject." \r\n
                                Message: "
.$first_name." ".$surname."\r\n You need to click on this following <a href=".$account_activation_link.">link</a> to activate your account. \r\n");
                                $headers = "From: " . $site_admin_email . "\r\n";
                       
                            if (!mail($to,$subject,$body,$headers))
                                {
                                        $_SESSION['error'] = "Sorry! We have failed to email you your account activation details. Please contact the website administrator!";
                                        exit();
                                }
                                else
                                {
                                        echo "<h3 style='text-align:center'>Thank you for your registration!<br /> Check your email for details on how to activate your account which you just registered.</h3>";
                                        exit();
                                }
                        }
            }
        }
}

?>

<!DOCTYPE html>
<html>
        <head>
                <title><?php $social_network_name ?> Signup Page</title>
        </head>
<body>
<div class ="container">

<?php
// Error Messages.
if (isset($_SESSION['error']) && !empty($_SESSION['error'])) {
        echo '<p style="color:red;">'.$_SESSION['error'].'</p>';
}
?>

<?php
//Session Messages.
if (isset($_SESSION['message']) && !empty($_SESSION['message'])) {
        echo '<p style="color:red;">'.$_SESSION['error'].'</p>';
}
?>

<?php
//Clear Registration Session.
function clear_registration_session()
        {
                //Clear the User Form inputs, Session Messages and Session Errors so they can no longer be used.
                unset($_SESSION['message']);
                unset($_SESSION['error']);
                unset($_POST);
                exit();
        }
?>

<form method="post" action="">
        <center><h2>Signup Form</h2></center>
        <div class="form-group">
                <center><label>Username:</label>
                <input type="text" placeholder="Enter a unique Username" name="username" required [A-Za-z0-9] value="<?php if(isset($_POST['username'])) { echo htmlentities($_POST['username']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Password:</label>
                <input type="password" placeholder="Enter a new Password" name="password" required [A-Za-z0-9]></center>
        </div>
        <div class="form-group">
                <center><label>Repeat Password:</label>
                <input type="password" placeholder="Repeat a new Password" name="password_confirmation" required [A-Za-z0-9]></center>
        </div>
                <div class="form-group">
                <center><label>Email:</label>
                <input type="email" placeholder="Enter your Email" name="email" required [A-Za-z0-9] value="<?php if(isset($_POST['email'])) { echo htmlentities($_POST['email']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Repeat Email:</label>
                <input type="email" placeholder="Repeat your Email" name="email_confirmation" required [A-Za-z0-9] value="<?php if(isset($_POST['email_confirmation'])) { echo htmlentities($_POST['email_confirmation']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>First Name:</label>
                <input type="text" placeholder="Enter your First Name" name="first_name" required [A-Za-z] value="<?php if(isset($_POST['first_name'])) { echo htmlentities($_POST['first_name']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Surname:</label>
                <input type="text" placeholder="Enter your Surname" name="surname" required [A-Za-z] value="<?php if(isset($_POST['surname'])) { echo htmlentities($_POST['surname']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Gender:</label>
                <input type="radio" name="gender" value="male" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Male<input type="radio" name="gender" value="female" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Female</center>
        </div>
        <center><button type="submit" class="btn btn-default" name="submit">Register!</button></center>
        <center><font color="red" size="3"><b>Already have an account ?</b><br><a href="login.php">Login here!</a></font></center>
</form>
</div>
</body>
</html>
 


Top
 Profile  
 
PostPosted: Mon Sep 18, 2017 6:25 pm 
Offline
Moderator
User avatar

Joined: Tue Nov 09, 2010 3:39 pm
Posts: 6391
Location: Montreal, Canada
UniqueIdeaMan wrote:
Celeraun,

If you check my original post, you will see 2 codes. First one is old version and second one is new version.

Your review was on the first bit of code (old version) as you made references to my code lines that exist in the old version and not in the new version.

No. I reviewed the 'new' version. Go back and see for yourself.

_________________
Supported PHP versions No longer supported versions


Top
 Profile  
 
PostPosted: Mon Sep 18, 2017 8:32 pm 
Offline
Moderator
User avatar

Joined: Tue Nov 09, 2010 3:39 pm
Posts: 6391
Location: Montreal, Canada
Don't ask me why, but I reviewed the new code also. Mostly the same issues as your last 'new' version.
Syntax: [ Download ] [ Hide ]
<?php

/*
ERROR HANDLING
*/

/**
 * Get rid of this. You're not actually using it
 */

declare(strict_types=1);
/**
 * This goes in your php.ini, not in runtime configurations
 */

ini_set('display_errors', '1');
ini_set('display_startup_errors', '1');
error_reporting(E_ALL);
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

/**
 * Try not to use includes. It hides dependencies and makes your code harder to
 * follow.
 */

include 'config.php';

//Step 1: Before registering User account, check if User is already registered or not.

//Check if User is already logged-in or not.
if (is_logged() === true) {
    /**
     * die() is not appropriate error handling
     * Redirect the user and display an error message
     */

        die("You are already logged-in! No need to register again!");
}

/**
 * This does not belong in the view. Move this to a controller
 */

if ($_SERVER['REQUEST_METHOD'] == "POST")
{
//Step 2: Check User Submitted Details.
       
        //Check if user made all the required inputs or not.
        if (isset($_POST["username"]) &&
           isset($_POST["password"]) &&
           isset($_POST["password_confirmation"]) &&
           isset($_POST["email"]) &&
           isset($_POST["email_confirmation"]) &&
           isset($_POST["first_name"]) &&
           isset($_POST["surname"]) &&
           isset($_POST["gender"])) {
                   
//Step  3: Check User details for matches against database. If no matches then validate inputs and register User account.
                   
                //Create variables based on user inputs.
                $username       = trim($_POST["username"]);
                $password       = $_POST["password"];
                $password_confirmation = $_POST["password_confirmation"];
                $email          = trim($_POST["email"]);
                /**
                 * Fix the crazy indentation. Code should be easy to read
                 */

        $email_confirmation = trim($_POST["email_confirmation"]);
        $first_name     = trim($_POST["first_name"]);
        $surname        = trim($_POST["surname"]);
                $gender         = $_POST["gender"];    
                $account_activation_code = sha1( (string) mt_rand(5, 30)); //Type Casted the INT to STRING on the 1st parameter of sha1 as it needs to be a STRING.
                /**
                 * Where are $site_domain and $social_network_name defined?
                 */

                $account_activation_link = "http://www.".$site_domain."/".$social_network_name."/activate_account.php?email=".$_POST['email']."&account_activation_code=".$account_activation_code."";
                $account_activation_status = 0; // 1 = active; 0 = not active.
                /**
                 * You're not encrypting the password, you're hashing it. Words matter.
                 */

        $hashed_password = password_hash($password, PASSWORD_DEFAULT); //Encrypt the password.
       
                /**
                 * This does not belong in your view. Separate your concerns. Move this into a model.
                 */

                //Select Username and Email to check against Mysql DB if they are already registered or not.
                $stmt = mysqli_prepare($conn, "SELECT usernames, emails FROM users WHERE usernames = ? OR emails = ?");
                mysqli_stmt_bind_param($stmt, 'ss', $username, $email);
                mysqli_stmt_execute($stmt);
                $result = mysqli_stmt_get_result($stmt);              
                $row = mysqli_fetch_array($result, MYSQLI_ASSOC);
       
                // Check if inputted Username is already registered or not.
                if ($row['usernames'] == $username) {
                        /**
                         * Why are you using sessions here?
                         */

                        $_SESSION['error'] = "That username is already registered.";
                        /**
                         * Much like die(), exit() is not appropriate for error handling
                         */

                        exit();
                // Check if inputted Username is between the required 8 to 30 characters long or not.
                /**
                 * Why elseif? What if there are multiple things wrong with the form?
                 * You'd currently require the user to submit once per error condition
                 * That's pretty awful UX
                 */

                } elseif (strlen($username) < 8 || strlen($username) > 30) {
                        $_SESSION['error'] = "Username must be between 8 to 30 characters long!";
                        exit();
                // Check if both inputted Emails match or not.
                } elseif ($email != $email_confirmation) {
                        $_SESSION['error'] = "Emails don't match!";
                        exit();
                // Check if inputed Email is valid or not.
                } elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
                        $_SESSION['error'] = "Invalid email! Insert your real Email in order for us to email you your account activation details.";
                        exit();
                // Check if inputted Email is already registered or not.
                } elseif ($row['emails'] == $email) {
                        /**
                         * Careful with this. You're potentially bleeding sensitive information here.
                         * You don't necessarily want the world to know who has an account
                         */

                        $_SESSION['error'] = "That email is already registered.";
                        exit();
                // Check if both inputted Passwords match or not.
                } elseif ($password != $password_confirmation) {
                        $_SESSION['error'] = "Passwords don't match.";
                        exit();
                // Check if Password is between 8 to 30 characters long or not.
                /**
                 * There is no benefit to setting an arbitrary maximum password length.
                 */

                } elseif (strlen($password) < 8 || strlen($password) > 30) {
                        $_SESSION['error'] = "Password must be between 6 to 30 characters long!";
                        exit();
                }
                else
                {
                    /**
                     * Move this out of the view layer
                     */

                        //Insert the user's inputs into Mysql database using php's sql injection prevention method "Prepared Statements".
                        /**
                         * Any reason you're using mysqli over PDO? PDO has a much nicer interface, making it easier to work with
                         */

                        $stmt = mysqli_prepare($conn, "INSERT INTO users(usernames, passwords, emails, first_names, surnames, genders, accounts_activations_codes, accounts_activations_statuses) VALUES (?, ?, ?, ?, ?, ?, ?, ?)");
                        mysqli_stmt_bind_param($stmt, 'sssssssi', $username, $hashed_password, $email, $first_name, $surname, $gender, $account_activation_code, $account_activation_status);
                        mysqli_stmt_execute($stmt);
                        /**
                         * Don't display debugging information to the user
                         */

                        echo "INSERTING";

                        //Check if user's registration data was successfully submitted or not.
                        if (!$stmt)
                        {
                                /**
                                 * Again with the sessions and the exit
                                 */

                                $_SESSION['error'] = "Sorry! Our system is currently experiencing a problem registering your account! You may try registering some other time.";
                                exit();
                        }
                        else
                        {
                                /**
                                 * Extract this to a method and move it out of the view
                                 */

                                //Email the account activation link for user to click it to confirm their email and activate their new account.
                                $to = $email;
                                $subject = "Your ".$site_name." account activation details!";
                                $body  = nl2br("
                                ===============================\r\n
                                "
.$site_name." \r\n
                                ===============================\r\n
                                From: "
.$site_admin_email."\r\n
                                To: "
.$email."\r\n
                                Subject: Yours "
.$subject." \r\n
                                Message: "
.$first_name." ".$surname."\r\n You need to click on this following <a href=".$account_activation_link.">link</a> to activate your account. \r\n");
                                $headers = "From: " . $site_admin_email . "\r\n";
                       
                            /**
                             * Seriously, fix your indentation. This is a mess.
                             */

                            if (!mail($to,$subject,$body,$headers))
                                {
                                        $_SESSION['error'] = "Sorry! We have failed to email you your account activation details. Please contact the website administrator!";
                                        exit();
                                }
                                else
                                {
                                    /**
                                     * Don't echo HTML
                                     */

                                        echo "<h3 style='text-align:center'>Thank you for your registration!<br /> Check your email for details on how to activate your account which you just registered.</h3>";
                                        exit();
                                }
                        }
            }
        }
}

?>

<!DOCTYPE html>
<html>
        <head>
                <title><?php /** echo? **/ $social_network_name ?> Signup Page</title>
        </head>
<body>
<div class ="container">

<?php
/**
 * Don't echo HTML
 */

// Error Messages.
if (isset($_SESSION['error']) && !empty($_SESSION['error'])) {
        echo '<p style="color:red;">'.$_SESSION['error'].'</p>';
}
?>

<?php
//Session Messages.
if (isset($_SESSION['message']) && !empty($_SESSION['message'])) {
        echo '<p style="color:red;">'.$_SESSION['error'].'</p>';
}
?>

<?php
/**
 * Move this
 */

//Clear Registration Session.
function clear_registration_session()
        {
                //Clear the User Form inputs, Session Messages and Session Errors so they can no longer be used.
                unset($_SESSION['message']);
                unset($_SESSION['error']);
                unset($_POST);
                exit();
        }
?>

<form method="post" action="">
        <center><h2>Signup Form</h2></center>
        <div class="form-group">
                <center><label>Username:</label>
                <input type="text" placeholder="Enter a unique Username" name="username" required [A-Za-z0-9] value="<?php if(isset($_POST['username'])) { echo htmlentities($_POST['username']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Password:</label>
                <input type="password" placeholder="Enter a new Password" name="password" required [A-Za-z0-9]></center>
        </div>
        <div class="form-group">
                <center><label>Repeat Password:</label>
                <input type="password" placeholder="Repeat a new Password" name="password_confirmation" required [A-Za-z0-9]></center>
        </div>
                <div class="form-group">
                <center><label>Email:</label>
                <input type="email" placeholder="Enter your Email" name="email" required [A-Za-z0-9] value="<?php if(isset($_POST['email'])) { echo htmlentities($_POST['email']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Repeat Email:</label>
                <input type="email" placeholder="Repeat your Email" name="email_confirmation" required [A-Za-z0-9] value="<?php if(isset($_POST['email_confirmation'])) { echo htmlentities($_POST['email_confirmation']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>First Name:</label>
                <input type="text" placeholder="Enter your First Name" name="first_name" required [A-Za-z] value="<?php if(isset($_POST['first_name'])) { echo htmlentities($_POST['first_name']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Surname:</label>
                <input type="text" placeholder="Enter your Surname" name="surname" required [A-Za-z] value="<?php if(isset($_POST['surname'])) { echo htmlentities($_POST['surname']); }?>"></center>
        </div>
        <div class="form-group">
                <center><label>Gender:</label>
                <input type="radio" name="gender" value="male" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Male<input type="radio" name="gender" value="female" <?php if(isset($_POST['gender'])) { echo 'checked'; }?> required>Female</center>
        </div>
        <center><button type="submit" class="btn btn-default" name="submit">Register!</button></center>
        <center><font color="red" size="3"><b>Already have an account ?</b><br><a href="login.php">Login here!</a></font></center>
</form>
</div>
</body>
</html>

_________________
Supported PHP versions No longer supported versions


Top
 Profile  
 
Display posts from previous:  Sort by  
Post new topic Reply to topic  [ 10 posts ] 

All times are UTC - 5 hours


Who is online

Users browsing this forum: Google [Bot] and 16 guests


You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot post attachments in this forum

Jump to:  
Powered by phpBB® Forum Software © phpBB Group