Improvements To Member Registration Site Reg.php

Guys,

I can’t believe it’s been 21 days since my last post on this thread!

I was working on the activate_account.php.
This is the script that activates the user’s member account once he clicks the link he gets emailed to confirm his email and activate his account.
Originally, that script was working fine. But tonight, I replaced some of the working code that had risk of sql injection. I was helped by mlucak89 on prepared statements on the register.php and it was working fine. Tonight, I added the prepared statements on the activate_account.php and wanted to see if it works. In order to test it, I tried opening a member account on my xampp but for some reason I get an error on the register.php which was working few days back. Check my previous post! I really haven’t made any changes to this file but changed a variable name tonight.
Anyway, here’s the full code and error:


<?php
include 'config.php';

// check if user is already logged in
if (is_logged() === true) {
	die("You are logged in, can't register.");
}

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"])) {

		// create random hash for email confirmation
	   	$account_activation_code = sha1(mt_rand(5, 30));
		// THIS IS NOT GETTING EMAILED !!!
		$account_activation_link = "http://www.'".$site_domain."'.com/'".$social_network_name."'/activate_account.php?email='".$_POST['email']."'&hash='".$account_activation_code."'";

   		// remove space in start of string
   		/*
		*	passwords and email are leaved unescaped here because
		*	if you put them into mysqli_real_escape_string they are not empty
   		*/
        $username 	= trim(mysqli_real_escape_string($conn, $_POST["username"]));
		$password 	= $_POST["password"];
		$password2 	= $_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 		= $_POST["email"];
        $email_confirmation = $_POST["email_confirmation"];
        $email2 	= trim(mysqli_real_escape_string($conn, $email)); // Escaped email for inserting into database.
        $account_activation = 0; // 1 = active | 0 = not active

        //Hashed Password.
		$hashed_password = password_hash("$password", PASSWORD DEFAULT);
        
		//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.";
		// 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 != $password2) {
			$_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_pass, $email2, $first_name, $surname, $gender, $registration_random_numbers, $account_activation);
			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 /> Redirecting you to the login page ...</h3>";

				//Redirect user to login page after 5 seconds.
				header("refresh:5;url=login.php");

				//Clear the Session Error so it can no longer be used.
				unset($_SESSION['error']);
				unset($_POST);
				exit(); 

				//Send accoutn 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=".$site_domain.'activate_account.php?hash='.$account_activation_link.">link</a> to confirm your email address and activate your account. \r\n");
				$headers = "From: " . $site_admin_email . "\r\n";
			
			    if (mail($to,$subject,$body,$headers)) {
			    	$_SESSION['error'] = "Registration sucessfull. Check your email for further instructions!";
			    } 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>

It said error on line 42. Line 42 looked like this:

$hashed_password = password_hash($password, PASSWORD DEFAULT);

I now changed it to:
$hashed_password = password_hash(“$password”, PASSWORD DEFAULT);
but error still remains. What do you think is wrong ?
Here is the error:
Parse error: syntax error, unexpected ‘DEFAULT’ (T_DEFAULT), expecting ‘,’ or ‘)’ in C:\xampp\htdocs\test\register_editing.php on line 42

And, here is my activate_account.php, do check the prepared statements. I have a feeling I got it wrong.


<?php
session_start();
require "conn.php";


//Grab User's (account activator's) email and account activation code from account activation link's url. Check for email and account activation code details in the account activation link's url.
if(!isset($_GET["email"], $_GET["registration_account_activation_code"]) === TRUE)
{
	$_SESSION['error']="Invalid Email Address! Invalid Account Activation Link! This email is not registered! Try registering an account if you do not already have one! <a href=\"register.php\">Register here!</a>";
	exit();
}
else
{
	$confirming_email = trim(mysqli_real_escape_string($conn,$_GET["email"])));
	$account_activation_code = trim(mysqli_real_escape_string($conn,$_GET["registration_random_numbers"])));
		
	//Check User's Confirmed Email and Account Activation Code against the "users" tbl to see if it has already been registered or not. Do this by selecting the Confirmed Email and Account Activation code to check against Mysql DB if they match or not.
	$stmt = mysqli_prepare($conn, "SELECT emails, accounts_activations_codes FROM users WHERE emails = ? OR accounts_activations_codes = ?");
	mysqli_stmt_bind_param($stmt, 'si', $confirming_email, $account_activation_code);
	mysqli_stmt_execute($stmt);
	
	//If the account activation code matches with the confirmed Email in the same row in the MySql DB then check if user has already activated his account or not.
	if (mysqli_stmt_insert_id($stmt)) 
	{	
		while($row = mysqli_fetch_assoc($result)) 
			{	  
				$db_account_activation = $row["account_activations"];				    
				if($db_account_activation != 0)	
				{
					echo "<script>alert('Since your account is already activated, why are you trying to activate it again ? Do not do that again and just login!')</script>";
					echo "Since your account is already activated, why are you trying to activate it again ? Do not do that again and just login from <a href=\"login.php\">this webpage</a> next time! Make a note of that webpage, ok ?";
					$conn->close();
					exit();
				}
				else
				{
					//Dump the account confirming User's details onto the same row in the "users" table.
					if (mysqli_stmt_insert_id($stmt)) 
					{	
						$stmt = "UPDATE users SET account_activations VALUES (?) WHERE emails = '".$db_confirmed_email."'";
						//Bind the variables to the parameter as strings an an integer.
						mysqli_stmt_bind_param($stmt, 'i', $account_activation);
						//Execute the statement.
						mysqli_stmt_execute($stmt);
		
						if (mysqli_stmt_insert_id($stmt)) 
						{
							echo "<h3 style='text-align:center'>Thank you for your confirming your email and activating your account.<br /> Redirecting you to the login page ...</h3>";
		
							$_SESSION["user"] = $db_username;
					
							//Redirect newly activated user to his/her account homepage.
							header("location:home.php");
						}		
					}
				}
			}		
	}
	else 
	{
		echo "<script>alert('Invalid Email Address or Invalid Account Activation Link! This Email $confirming_email was not pending registration with this Account Activation Code $account_activation_code! Try registering an account!')</script>";
		echo "Invalid Email Address or Invalid Account Activation Link! This Email $confirming_email was not pending registration with this Account Activation Code $account_activation_code! 
		Try registering an account if you have not already done so! <a href=\"register.php\">Register here!</a>";
    	$conn->close();
		exit();	
	}
}

?>

Basically, when you register an account, the registration.php script ads “0” to column “account_activations” in “users” tbl and emails you the account activation link.
When you click that link and confirm your email, the account_activation.php script is supposed to UPDATE the “0” to “1” on the “account_activations” column. That’s all there is to it. A very simple script.

Thanks for your all help!

This should have an underscore, not a space.

$hashed_password = password_hash($password, PASSWORD_DEFAULT);

Also $password does not need quotes.

1 Like

In this bit of code

//Dump the account confirming User's details onto the same row in the "users" table.
  if (mysqli_stmt_insert_id($stmt)) 
  {	
    $stmt = "UPDATE users SET account_activations VALUES (?) WHERE emails = '".$db_confirmed_email."'";
    //Bind the variables to the parameter as strings an an integer.
    mysqli_stmt_bind_param($stmt, 'i', $account_activation);
    //Execute the statement.
    mysqli_stmt_execute($stmt);

there are two issues. You have omitted the mysqli_prepare() function, and for some reason you’ve only bound one parameter, and used string concatenation for the email address.

3 Likes

You just need to make query like this

UPDATE users SET account_activations = 1 WHERE emails = '$db_confirmed_email'"

because you changing only 1 field from 0 to 1.

Edit:

And change this

mysqli_stmt_bind_param($stmt, 'i', $account_activation);

to

mysqli_stmt_bind_param($stmt, 's', $db_confirmed_email');

Note : i = integer, s = string

1 Like

SamA74,

Thanks for spotting my typo! I’ve fixed it. :slight_smile:

mlucak89 & droopsnoot,

Thanks for your inputs on the account_activation.php.
Right now, I can’t test how your suggestions work on account_activations.php because I’m having a new issue on the register.php.

The script is set to work once you’ve clicked the “register” button:

Line 9

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

Else, give error (line: 115; Scroll right to the bottom as it is just a few lines before the html form)

else 
			{
				$_SESSION['error'] = "There was a problem in trying to register you! Try again some other time.";
			}

Now, my question is, what kind of possibilities could occur that will trigger the ELSE and it’s error message ? I’m asking because for some reason the ELSE is getting triggered and I can’t see why.
Do programmers here, mind checking the script out on your localhosts and see if it happens to you too ?

Here’s the full updated script:

register.php


<?php
include 'config.php';

// check if user is already logged in
if (is_logged() === true) {
	die("You are logged in. Can't register!");
}

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"])) {

		// create random hash for email confirmation
	   	$account_activation_code = sha1(mt_rand(5, 30));
		// THIS IS NOT GETTING EMAILED !!!
		$account_activation_link = "http://www.'".$site_domain."'.com/'".$social_network_name."'/activate_account.php?email='".$_POST['email']."'&hash='".$account_activation_code."'";

   		// remove space in start of string
   		/*
		*	passwords and email are leaved unescaped here because
		*	if you put them into mysqli_real_escape_string they are not empty
   		*/
        $username 	= trim(mysqli_real_escape_string($conn, $_POST["username"]));
		$password 	= $_POST["password"];
		$password2 	= $_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 		= $_POST["email"];
        $email_confirmation = $_POST["email_confirmation"];
        $email2 	= trim(mysqli_real_escape_string($conn, $email)); // Escaped email for inserting into database.
        $account_activation = 0; // 1 = active | 0 = not active

        //Hashed Password.
		$hashed_password = password_hash($password, PASSWORD_DEFAULT);
        
		//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.";
		// 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 != $password2) {
			$_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_pass, $email2, $first_name, $surname, $gender, $registration_random_numbers, $account_activation);
			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 /> Redirecting you to the login page ...</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=".$site_domain.'activate_account.php?hash='.$account_activation_link.">link</a> to confirm your email address and activate your account. \r\n");
				$headers = "From: " . $site_admin_email . "\r\n";
			
			    if (mail($to,$subject,$body,$headers)) {
			    	$_SESSION['error'] = "Registration sucessfull. Check your email for further instructions!";
					
					//Redirect user to login page after 5 seconds.
					header("refresh:5;url=login.php");

					//Clear the Session Error so it can no longer be used.
					unset($_SESSION['error']);
					unset($_POST);
					exit();
			    } 
				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>

So, you are saying, it should be like this:


if (mysqli_stmt_insert_id($stmt)) 
					{	
						$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);

Correct ?

Fellow Programmers, :slight_smile:

activate_account_edited.php (3.7 KB)

I’ve attached the activate_account.php just incase anybody wants to have a look at it with line numbers since this forum is not showing the line numbers.
Worthy of note is line 39 where I made a question if line 40 is really necessary or not.

register_editing.php (8.1 KB)

Thanks. :wink:

Yeah, I know what the “s” and “i” stand for.
I’ve attached my latest updates on my previous post just incase anybody finds it difficult finding the lines I’m referring to in my latest posts since this forum is not lining the codings.
I hope the scripts work on your ends guys. :slight_smile:

If you have any feature suggestions then by all means do make your suggestions.
Remember, both scripts were working fine before sanitisation. After it, I’m encountering a few problems and I know it’s due to my mistakes somewhere.

This is a problem with query if (mysqli_stmt_insert_id($stmt)) { this line, that means that last inserted id is fail, so probably is problem in your query.

Try to throw error by wrapping all insert code and mail code into this

try {
    // your code
    //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_pass, $email2, $first_name, $surname, $gender, $registration_random_numbers, $account_activation);
		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 /> Redirecting you to the login page ...</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=".$site_domain.'activate_account.php?hash='.$account_activation_link.">link</a> to confirm your email address and activate your account. \r\n");
			$headers = "From: " . $site_admin_email . "\r\n";
		
		    if (mail($to,$subject,$body,$headers)) {
		    	$_SESSION['error'] = "Registration sucessfull. Check your email for further instructions!";
				
				//Redirect user to login page after 5 seconds.
				header("refresh:5;url=login.php");

				//Clear the Session Error so it can no longer be used.
				unset($_SESSION['error']);
				unset($_POST);
				exit();
		    } 
			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.";
		}
} catch (Exception $e) {
    // this will give you a error and tell where it is
    echo 'Caught exception: ',  $e->getMessage(), "\n";
}

The ELSE that sets the session variable is not from whether or not the script was triggered by a POST, it’s from further in the nesting. I may have counted wrongly, but I think that else is being triggered from this if():

//Check if user's registration data was successful submitted or not.
if (mysqli_stmt_insert_id($stmt)) {

I am tempted to ask whether this is down to column names - didn’t you say many, many posts ago that you’d renamed the columns to remove the ‘s’ on the end of the names, on at least some of them? Although as the earlier query works, maybe it’s not that.

(ETA - as @mlukac89 said above, now I read it properly).

Also there’s another typo. This bit of code

//Hashed Password.
$hashed_password = password_hash($password, PASSWORD_DEFAULT);

doesn’t tie with this part

mysqli_stmt_bind_param($stmt, 'sssssssi', $username, $hashed_pass, $email2, $first_name, $surname, $gender, $registration_random_numbers, $account_activation);
                                                                ^ here 

So maybe if the password column is a required one, and you pass a null variable to it, it won’t run.

3 Likes

Might be time to take the next step and post your code to a github repository. It is extremely difficult to actually follow your code using bits and snippets.

And if really want to do yourself a favor, install the Doctrine Database Abstraction Layer: http://docs.doctrine-project.org/projects/doctrine-dbal/en/latest/reference/introduction.html You will be amazed at how much of your sql boilerplate code simple goes away.

1 Like

Thanks droopsnoot!

Silly me! It’s my typo again! :banghead:
Originally, my registration.php, login.php and activate_account.php were working but they all had one problem. They weren’t sanitized and so sql injection was very simple to do on them. You can see, the scripts are procedural style and using mysqli_ as the youtube tutorials were based on them. I did find other tutorials and managed to add prepared statements but that part was by pdo or oop style and so I asked in this thread for help to turn it into mysqli_ and procedural style and mlukac89 responded by adding prepared statements procedural style on register.php. I then tried copying his method onto activate_account.php and you can see how I’m messing things up. When he hashed, he used “$hashed_pass” but I don’t like short-hand and so edited on some places to “$hashed_password” but forgot to replace it on the spot you just spotted. :unhappy:

Anyway, I’ll try fixing according to you 2 person’s suggestions but I have a feeling I will get a lot of hiccups and experience some rough rides on the way and so I appreciate it when you guys stick around in this thread. It is becoming a good learning curve. I may have a few more questions and may take a few more bumps on the way till this is properly sorted-out. :wonky:

After that, I’ll work on the viral traffic etc. parts adding my own features. So, stay tuned to see what’s coming ahead.

Cheers!

Thanks for the link but what is it really about ? I checked out the link but didn’t understand it. I’m a beginner.
I notice pdo and oop is mentioned. My scripts are in mysqli_ and procedural as of now as beginner tutorials are based that way.
However, I saved your link as I have a feeling it would be handy when I move-onto pdo and oop style.

I get this error now after adding that line of code to show me the error:

Parse error: syntax error, unexpected ‘catch’ (T_CATCH) in C:\xampp\htdocs\test\register_editing.php on line 118


<?php
include 'config.php';

// check if user is already logged in
if (is_logged() === true) {
	die("You are logged in. Can't register!");
}

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"])) {

		// create random hash for email confirmation
	   	$account_activation_code = sha1(mt_rand(5, 30));
		// THIS IS NOT GETTING EMAILED !!!
		$account_activation_link = "http://www.'".$site_domain."'.com/'".$social_network_name."'/activate_account.php?email='".$_POST['email']."'&hash='".$account_activation_code."'";

   		// remove space in start of string
   		/*
		*	passwords and email are leaved unescaped here because
		*	if you put them into mysqli_real_escape_string they are not empty
   		*/
        $username 	= trim(mysqli_real_escape_string($conn, $_POST["username"]));
		$password 	= $_POST["password"];
		$password2 	= $_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 		= $_POST["email"];
        $email_confirmation = $_POST["email_confirmation"];
        $email2 	= trim(mysqli_real_escape_string($conn, $email)); // Escaped email for inserting into database.
        $account_activation = 0; // 1 = active | 0 = not active

        //Hashed Password.
		$hashed_password = password_hash($password, PASSWORD_DEFAULT);
        
		//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.";
		// 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 != $password2) {
			$_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, $email2, $first_name, $surname, $gender, $registration_random_numbers, $account_activation);
			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 /> Redirecting you to the login page ...</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=".$site_domain.'activate_account.php?hash='.$account_activation_link.">link</a> to confirm your email address and activate your account. \r\n");
				$headers = "From: " . $site_admin_email . "\r\n";
			
			    if (mail($to,$subject,$body,$headers)) {
			    	$_SESSION['error'] = "Registration sucessfull. 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.";
			}
	    }
		catch (Exception $e) {
		// this will give you a error and tell where it is
		echo 'Caught exception: ',  $e->getMessage(), "\n";
		}
	}
}


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

register_editing.php (8.2 KB)

Tried also adding the code to show error, right at the end of the php code, just before the html form, but no luck. Like so:


catch (Exception $e) {
		// this will give you a error and tell where it is
		echo 'Caught exception: ',  $e->getMessage(), "\n";
		}
?>
<!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>

Still get the same error:

Parse error: syntax error, unexpected ‘catch’ (T_CATCH), expecting end of file in C:\xampp\htdocs\test\register_editing.php on line 121

Interestingly, it seems that a catch does not need to have a corresponding try though I have never seen any code where they didn’t

http://php.net/manual/en/language.exceptions.php

Code may be surrounded in a try block, to facilitate the catching of potential exceptions.

Maybe someone else knows how to use a catch without a try? If so I’d like to see how it’s done.

Other than that, I think you should wrap the code block where the exception could come from in a try block.

2 Likes

You mean the “try {” is part of the code ?
I thought that was just an indication to me by mlukac89.

Anyway, I added that on line 2 just now but no luck:


<?php
try{
	include 'config.php';

// check if user is already logged in
if (is_logged() === true) {
	die("You are logged in. Can't register!");
}

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"])) {

		// create random hash for email confirmation
	   	$account_activation_code = sha1(mt_rand(5, 30));
		// THIS IS NOT GETTING EMAILED !!!
		$account_activation_link = "http://www.'".$site_domain."'.com/'".$social_network_name."'/activate_account.php?email='".$_POST['email']."'&hash='".$account_activation_code."'";

   		// remove space in start of string
   		/*
		*	passwords and email are leaved unescaped here because
		*	if you put them into mysqli_real_escape_string they are not empty
   		*/
        $username 	= trim(mysqli_real_escape_string($conn, $_POST["username"]));
		$password 	= $_POST["password"];
		$password2 	= $_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 		= $_POST["email"];
        $email_confirmation = $_POST["email_confirmation"];
        $email2 	= trim(mysqli_real_escape_string($conn, $email)); // Escaped email for inserting into database.
        $account_activation = 0; // 1 = active | 0 = not active

        //Hashed Password.
		$hashed_password = password_hash($password, PASSWORD_DEFAULT);
        
		//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.";
		// 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 != $password2) {
			$_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, $email2, $first_name, $surname, $gender, $registration_random_numbers, $account_activation);
			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 /> Redirecting you to the login page ...</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=".$site_domain.'activate_account.php?hash='.$account_activation_link.">link</a> to confirm your email address and activate your account. \r\n");
				$headers = "From: " . $site_admin_email . "\r\n";
			
			    if (mail($to,$subject,$body,$headers)) {
			    	$_SESSION['error'] = "Registration sucessfull. 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.";
			}
	    }
	}
}

		catch (Exception $e) {
		// this will give you a error and tell where it is
		echo 'Caught exception: ',  $e->getMessage(), "\n";
		}
?>
<!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>

register_editing.php (8.2 KB)

I get the same error:
Parse error: syntax error, unexpected ‘catch’ (T_CATCH) in C:\xampp\htdocs\test\register_editing.php on line 122

Tried by adding on line 72 instead of line 2 and no luck too.
I get the same error:
Parse error: syntax error, unexpected ‘catch’ (T_CATCH) in C:\xampp\htdocs\test\register_editing.php on line 122


<?php
include 'config.php';

// check if user is already logged in
if (is_logged() === true) {
	die("You are logged in. Can't register!");
}

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"])) {

		// create random hash for email confirmation
	   	$account_activation_code = sha1(mt_rand(5, 30));
		// THIS IS NOT GETTING EMAILED !!!
		$account_activation_link = "http://www.'".$site_domain."'.com/'".$social_network_name."'/activate_account.php?email='".$_POST['email']."'&hash='".$account_activation_code."'";

   		// remove space in start of string
   		/*
		*	passwords and email are leaved unescaped here because
		*	if you put them into mysqli_real_escape_string they are not empty
   		*/
        $username 	= trim(mysqli_real_escape_string($conn, $_POST["username"]));
		$password 	= $_POST["password"];
		$password2 	= $_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 		= $_POST["email"];
        $email_confirmation = $_POST["email_confirmation"];
        $email2 	= trim(mysqli_real_escape_string($conn, $email)); // Escaped email for inserting into database.
        $account_activation = 0; // 1 = active | 0 = not active

        //Hashed Password.
		$hashed_password = password_hash($password, PASSWORD_DEFAULT);
        
		//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.";
		// 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 != $password2) {
			$_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 {

		try {
			//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, $email2, $first_name, $surname, $gender, $registration_random_numbers, $account_activation);
			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 /> Redirecting you to the login page ...</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=".$site_domain.'activate_account.php?hash='.$account_activation_link.">link</a> to confirm your email address and activate your account. \r\n");
				$headers = "From: " . $site_admin_email . "\r\n";
			
			    if (mail($to,$subject,$body,$headers)) {
			    	$_SESSION['error'] = "Registration sucessfull. 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.";
			}
	    }
	}
}

		catch (Exception $e) {
		// this will give you a error and tell where it is
		echo 'Caught exception: ',  $e->getMessage(), "\n";
		}


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

register_editing.php (8.3 KB)

I have a feeling, I’m doing something wrong here. But where ?

@mlukac89, DO NOT use try catch for the error reporting. It is pointless and harmful at the same time.

1 Like

Code may be surrounded in a try block, to facilitate the catching of potential exceptions.

I’m not sure about this. :thinking:
Is it saying that a try before a catch is optional, or that using the whole try/catch thing is optional?

I was going to say that the catch with no try was the cause of the problem.

Looks like the OP added the try but it did not work, though it could be nested wrong in the brackets, hard to tell with the way it’s indented.

That would be another option, remove the catch. I think try/catch has its uses, but this is not it.

1 Like

It is, the nesting is wrong at least in the second example. The indenting does make it difficult, but I just mentally count brackets opening (+1) and closing (-1) and when it’s added in the second code, my mental count when the catch appears is -2, so it needs to be two close-brackets further up. Ish.

3 Likes

Thank you everyone for your inputs.
Let’s try to make it work without the Try->Catch.
Any suggestions how I could re-code it where the problem is occuring ?

You know, when I used to build .exe bots with Ubot Studio, the codes used to go to thousands of lines sometimes with many IF conditions (like in this case) and it was hard to figure-out which IF was causing the problem and whether the THEN or the ELSE was getting triggered, was hard to figure-out. So, do you know what I used to do ? I used to write ALERTS (similar to php echo/print) and I used to write different messages for each IF->Then/Else. And then I used to run the script and see which ALERTS I get. That way, I was easily tracking which ones were getting triggered. I thought I might try that last night but didn’t bother as I thought experts here might have a better php tactic which I’ll hear about it here and get introduced to it. That TRY->Catch is one thing new to me. Any other tactic php has up it’s sleeves ? If not, then I might aswell try my old bot tactic now.
Another thing I used to do while botting is that, I used to write logs in the script flow. Thus recording, what the bot is doing, onto a txt file on the user’d hdd. I’m thinking of doing the same with php where the script flow gets recorded onto mysql or admin account. Not the whole flow of the script but only those parts where there is a malfunction vulnerability. That way, admin can see which user’s account is misbehaving how.
If you think this is a good tactic and you learnt something from a newbie then give a vote or whatever that indicates you appreciated this post.

Thanks :slight_smile: