Unexpected end of file in php code

Hello,

I am working on some code, trying to get a system setup where a user can login either as basic user or admin. I am getting this error: Parse error : syntax error, unexpected end of file in C:\Program Files\Projects\register.php on line 156

Here is the code
<?php
// Include config file
require_once “config.php”;

// Define variables and initialize with empty values
$Name1 = $password = $confirm_password = "";
$userid="1";
$username_err = $password_err = $confirm_password_err = "";

// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST")
{

// Validate username
if(empty(trim($_POST["Name"])))
{
    $username_err = "Please enter a username.";
}
else
{
    // Prepare a select statement
    $sql = "SELECT Name FROM users WHERE Name = ?";

    if($stmt = mysqli_prepare($link, $sql))
    {
        // Bind variables to the prepared statement as parameters
      mysqli_stmt_bind_param($stmt,"s",$param_Name);

        // Set parameters
        $param_Name = trim($_POST["Name"]);

        // Attempt to execute the prepared statement
        if(mysqli_stmt_execute($stmt))
        {
            /* store result */
            mysqli_stmt_store_result($stmt);

            if(mysqli_stmt_num_rows($stmt) == 1)
            {
                $username_err = "This username is already taken.";
            }
            else
            {
                $Name1 = trim($_POST["Name"]);
            }
        }
        else
        {
            echo "Oops! Something went wrong. Please try again later.";
        }
    }


    // Close statement
    mysqli_stmt_close($stmt);
}

// Validate password
if(empty(trim($_POST["password"]))){
    $password_err = "Please enter a password.";
} elseif(strlen(trim($_POST["password"])) < 6){
    $password_err = "Password must have atleast 6 characters.";
} else{
    $password = trim($_POST["password"]);
}

// Validate confirm password
if(empty(trim($_POST["confirm_password"]))){
    $confirm_password_err = "Please confirm password.";
}
else
{
    $confirm_password = trim($_POST["confirm_password"]);
    if(empty($password_err) && ($password != $confirm_password)){
        $confirm_password_err = "Password did not match.";
 }


// Check input errors before inserting in database
if(empty($username_err) && empty($password_err) && empty($confirm_password_err))
{

    // Prepare an insert statement
    $sql = "INSERT INTO users (Name, password,userid) VALUES (?, ?,?)";

    if($stmt = mysqli_prepare($link, $sql))
    {
        // Bind variables to the prepared statement as parameters
       mysqli_stmt_bind_param($stmt,"ss", $param_Name, $param_password,$param_userid);

        // Set parameters
        $param_Name = $Name1;
        $param_password = password_hash($password, PASSWORD_DEFAULT); // Creates a password hash
        $param_userid= $userid;

        // Attempt to execute the prepared statement
        if(mysqli_stmt_execute($stmt))
        {
            // Redirect to login page
            header("location: login2.php");
        }
        else
        {
            echo "Something went wrong. Please try again later.";
        }
    }

    // Close statement
    mysqli_stmt_close($stmt);


// Close connection
mysqli_close($link);

?>

Sign Up body{ font: 14px sans-serif; } .wrapper{ width: 350px; padding: 20px; }

Sign Up

Please fill this form to create an account.

" method="post">
Username <?php echo $username_err; ?>
Password <?php echo $password_err; ?>
Confirm Password <?php echo $confirm_password_err; ?>

Already have an account? Login here.

This error is usually caused by mismatched {} or mismatched quotes. In the case of the posted code, there are at least three missing closing }'s.

It would help if you properly indented your code so that the matching opening and closing {}'s are lined up.

This code is also filled with unnecessary and repetitive logic and some missing and incorrect items. Some suggestions that will greatly simplify the code, making it easier to find and fix problems -

  1. Use an array to hold validation errors.
  2. Trim all the input data at once, using one statement.
  3. Use exceptions to handle database statement errors, and in most cases let php catch and handle the exception, where it will use its error related settings to control what happens with the actual error information. The exception to this rule is when inserting/updating user submitted data. See the next item on this list.
  4. Don’t try to SELECT data to decide if it already exists. Just define the the column(s) in your database table as unique index(es), attempt to insert the data, and detect if there was a duplicate key error.
  5. The header() redirect needs an exit statement to stop program execution.
  6. There’s generally no need to close database connections as php will automatically do this when the script ends.
  7. Switch to the much simpler and more consistent PDO database extension. You have a mistake one of the …bind_param() statements that will disappear if you switch to the PDO extension.
  8. You need to apply htmlentities() to all dynamic values being output on the web page.

If I/others get a chance, we will post an example showing these suggestions.

Here is what the code would look like with the above suggestions -

<?php

// note: the following example uses the PDO extension.
// when you make the connection using PDO, set the error mode to exceptions, set emulated prepared queries to false, and set the default fetch mode to assoc

// Include config file
require "config.php";

// Define variables and initialize with empty values
$errors = []; // define array to hold validation errors
$post = []; // define array to hold a trimmed working copy of the form data

// Processing form data when form is submitted
if($_SERVER["REQUEST_METHOD"] == "POST")
{
	// trim all the form data. note: if any of the form fields are arrays, use a recursive trim call-back function here instead of php's trim function
	$post = array_map('trim',$_POST);

	// Validate username
	if($post['Name'] == '')
	{
		$errors['Name'] = "Please enter a username.";
	}

	// Validate password
	if($post["password"] == '')
	{
		$errors['password'] = "Please enter a password.";
	}
	elseif (strlen($post["password"]) < 6)
	{
		$errors['password'] = "Password must have at least 6 characters.";
	}

	// Validate confirm password
	if($post["confirm_password"] == '')
	{
		$errors['confirm_password'] = "Please enter a confirm password.";
	}

	// compare password/confirm_password
	if(empty($errors['password']) && empty($errors['confirm_password']) && $post['password'] != $post['confirm_password'])
	{
		$errors['confirm_password'] = "Password and Confirm Password do not match.";
	}

	// if no errors, use the submitted data
	if(empty($errors))
	{
		// Prepare an insert statement
		$sql = "INSERT INTO users (Name, password) VALUES (?,?)";
		$stmt = $pdo->prepare($sql);

		try { // a 'local' try/catch to handle a specific error type
			$stmt->execute([
				$post['Name'],
				password_hash($post['password'], PASSWORD_DEFAULT)
				]);
		} catch (PDOException $e) {
			if($e->errorInfo[1] == 1062) // duplicate key error number 
			{
				$errors['Name'] = "This username is already taken.";
			} else { 
				throw $e; // re-throw the pdoexception if not handled by this logic
			}
		}
	}
	
	// if no errors, success
	if(empty($errors))
	{
		header("location: login2.php");
		exit;
	}
}

?>
<!DOCTYPE html>
<html lang="en">
<head>
	<meta charset="UTF-8">
	<title>Sign Up</title>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.css">
	<style type="text/css">
		body{ font: 14px sans-serif; }
		.wrapper{ width: 350px; padding: 20px; }
	</style>
</head>
<body>
	<div class="wrapper">
		<h2>Sign Up</h2>
		<p>Please fill this form to create an account.</p>
		<form method="post">
		<div class="form-group <?php echo !empty($errors['Name']) ? 'has-error' : ''; ?>">
			<label>Username</label>
			<input type="text" name="Name" class="form-control" value="<?php echo htmlentities($post['Name'] ?? '',ENT_QUOTES); ?>">
			<span class="help-block"><?php echo $errors['Name'] ?? ''; ?></span>
		</div>
		<div class="form-group <?php echo !empty($errors['password']) ? 'has-error' : ''; ?>">
			<label>Password</label>
			<input type="password" name="password" class="form-control" value="<?php echo htmlentities($post['password'] ?? '',ENT_QUOTES); ?>">
			<span class="help-block"><?php echo $errors['password'] ?? ''; ?></span>
		</div>
		<div class="form-group <?php echo !empty($errors['confirm_password']) ? 'has-error' : ''; ?>">
			<label>Confirm Password</label>
			<input type="password" name="confirm_password" class="form-control" value="<?php echo htmlentities($post['confirm_password'] ?? '',ENT_QUOTES); ?>">
			<span class="help-block"><?php echo $errors['confirm_password'] ?? ''; ?></span>
		</div>
		<div class="form-group">
			<input type="submit" class="btn btn-primary" value="Submit">
			<input type="reset" class="btn btn-default" value="Reset">
		</div>
		<p>Already have an account? <a href="login.php">Login>.</p>
		</form>
	</div>
</body>
</html>
1 Like
Sponsor our Newsletter | Privacy Policy | Terms of Service