My Registration Page Submission Is Giving Blank Page

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
UniqueIdeaMan
Forum Contributor
Posts: 197
Joined: Wed Jan 18, 2017 3:43 pm

My Registration Page Submission Is Giving Blank Page

Post by UniqueIdeaMan »

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:

Code: Select all

<?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:

Code: Select all

<?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 ?
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: My Registration Page Submission Is Giving Blank Page

Post by Celauran »

There's plenty wrong with it. Is there a specific problem you're trying to resolve?
UniqueIdeaMan
Forum Contributor
Posts: 197
Joined: Wed Jan 18, 2017 3:43 pm

Re: My Registration Page Submission Is Giving Blank Page

Post by UniqueIdeaMan »

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.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: My Registration Page Submission Is Giving Blank Page

Post by Celauran »

Code review? Okie dokie.

Code: Select all

<?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>
UniqueIdeaMan
Forum Contributor
Posts: 197
Joined: Wed Jan 18, 2017 3:43 pm

Re: My Registration Page Submission Is Giving Blank Page

Post by UniqueIdeaMan »

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:

Code: Select all

[b]"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"[/b]
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.

Code: Select all

[b]<?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();
	}
?>[/b]

2. You mention:

Code: Select all

/**
 * What? No. Use autoloading
 */
include 'config.php';
Care to elaborate more by giving a sample snippet so I understand you better ?


3. You mention:

Code: Select all

[b]// 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
 */[/b]
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:

Code: Select all

[b]" * If you're going to call trim on everything in the array, consider using array_map
                 */
"[/b]
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:

Code: Select all

[b]"/**
                 * What if the query fails and $result is false?
                 */         
"[/b]
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:

Code: Select all

[b]"/**
                 * Why else? What if there are multiple problems with the registration?
                 */
"[/b]
Actually, another programmer added these when he edited my script. He is no longer available. I will ponder more about this.


7.
You mention:

Code: Select all

[b]" * 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 {
"[/b]
Mmm. Usually reg pages ask for this and so I just copied them. Curious, what would you do here ?


8.
You mention:

Code: Select all

"
//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>";
"
How do you mean ? A sample snippet would indeed make me remember things like this more often.


9.
You mention:

Code: Select all

[b]"
//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!";
"[/b]
Where should I remove it to ?
10.
You mention:

Code: Select all

[b]<?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>';
}

?>[/b]
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
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: My Registration Page Submission Is Giving Blank Page

Post by Celauran »

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:

Code: Select all

<?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.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: My Registration Page Submission Is Giving Blank Page

Post by Celauran »

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:

Code: Select all

/**
 * 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:

Code: Select all

// 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:

Code: Select all

/* 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:

Code: Select all

[b]" * 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 {
"[/b]
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:

Code: Select all

//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:

Code: Select all

<?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.
UniqueIdeaMan
Forum Contributor
Posts: 197
Joined: Wed Jan 18, 2017 3:43 pm

Re: My Registration Page Submission Is Giving Blank Page

Post by UniqueIdeaMan »

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!

Code: Select all

<?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>
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: My Registration Page Submission Is Giving Blank Page

Post by Celauran »

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.
User avatar
Celauran
Moderator
Posts: 6427
Joined: Tue Nov 09, 2010 2:39 pm
Location: Montreal, Canada

Re: My Registration Page Submission Is Giving Blank Page

Post by Celauran »

Don't ask me why, but I reviewed the new code also. Mostly the same issues as your last 'new' version.

Code: Select all

<?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>
Post Reply