Simple User Registration in PHP

User registration is a feature that allows users to create their own accounts to access restricted areas of an application. Learn in this post how to sign up users in PHP in simple and easy steps.

Simple User Registration in PHP

Many web applications use a user registration feature to allow users to access certain restricted areas of the application that only registered users are allowed to access such as the dashboard, profile, and other application related pages. In this post, we will create a user registration system in PHP following a few steps. We will implement user email verification to verify user authenticity.

 

How to Register a User in PHP (Step-by-Step)

It is easy to create a user registration system in PHP by following a few simple steps. We will create an interface for the user to enter details and handle the form submission on the server side with a password comparison check, and we will also check if the email is not already used in the database.

 

Step 1: Database Structure

We need a database table for users with an appropriate schema where we save user data. Our users.sql is the structure we need with id, name, email, token, and is_verified columns.

users.sql
CREATE TABLE IF NOT EXISTS `users` (
`id` bigint NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` varchar(100) NOT NULL,
`email` varchar(150) NOT NULL UNIQUE,
`password` varchar(255) NOT NULL,
`token` varchar(255) DEFAULT NULL,
`is_verified` tinyint(1) DEFAULT '0'
);
 

Step 2: Database Configuration Constants

We also need some constants that we can use in our server-side script to connect to the database and create a verification link to verify the email address of the user.

<?php
define('BASE_URL', 'https://' . $_SERVER['SERVER_NAME']); // Application base url
define('DB_HOST', 'DATABASE_HOST'); // Database host
define('DB_NAME', 'DATABASE_NAME'); // Database name
define('DB_USER', 'DATABASE_USERNAME'); // Username for database
define('DB_PASSWORD', 'DATABASE_PASSWORD'); // Password for database
 

Step 3: Create User Register Form (HTML)

Now we create a user registration form where users can enter details for registration. The form will contain name, email, password, and password_confirm fields to match both passwords the user entered. This form will be handled on the server-side by another PHP script for user registration.

index.php 
<?php
if (!session_id()) {
session_start();
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Simple User Registration in PHP - Demo</title>
<meta content="text/html; charset=UTF-8" http-equiv="Content-Type"/>
<meta content="width=device-width, initial-scale=1, maximum-scale=1" name="viewport"/>
<link rel="stylesheet" href="css/style.css"/>
</head>
<body>
<section class="section py-4">
<div class="container">
<?php if (isset($_SESSION['flash'])) {?>
<div class="alert alert-<?=isset($_SESSION['flash']['error']) ? 'red' : 'green';?>">
<?=$_SESSION['flash']['message'];?>
</div>
<?php
unset($_SESSION['flash']);
} ?>

<form class="register-form" method="POST" action="process-register.php">
<div class="mb-4">
<input type="text" name="name" class="form-control" placeholder="Full name..." required="required"/>
</div>

<div class="mb-4">
<input type="email" name="email" class="form-control" placeholder="Email..." required="required"/>
</div>

<div class="mb-4">
<input type="password" name="password" class="form-control" placeholder="Password..." required="required"/>
</div>

<div class="mb-4">
<input type="password" name="password_confirm" class="form-control" placeholder="Confirm password..." required="required"/>
</div>

<button type="submit" class="btn btn-green">
Register
</button>
</form>
</div>
</section>
</body>
</html>
 

Step 4: Process User Registration on Server-Side (PHP)

This script handles the form submission and processes data to register users in the PHP application. The script has a few checks and email verification link generation to verify user email authenticity. Following is the step-by-step code explanation:

  • Start a session if not already started.
  • Include the constants configuration file.
  • Sanitize user submitted values using the filter_input_array() function of PHP.
  • Establish a database connection and create $name$email, $password and $token variables from user submitted values.
  • Generate a random token for email verification.
  • Check if both passwords the user entered are the same. Redirect back with an error message if they are not the same.
  • Check if a user with the same email already exists. If the email is already in use, redirect back with an error message.
  • Save the user to the database table with parameterized queries.
  • Prepare an HTML message to send for email verification with a verification token.
  • Send the registration verification email to the user's email address.
  • Finally, redirect back with a success message.
process-registration.php
<?php
if (!session_id()) {
session_start();
}

include_once 'constants.php';

$redirect_back_url = filter_var($_SERVER['HTTP_REFERER'], FILTER_SANITIZE_URL);

// Sanitize input array
$post = filter_input_array(INPUT_POST);

if (!empty($post)) {
$db_connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die(mysqli_connect_error());

// Prepare user data variables
$name = trim($post['name']);
$email = trim($post['email']);
$password = password_hash($post['password'], PASSWORD_DEFAULT);
$token = bin2hex(random_bytes(32));

// If passwords do not match return back
if (strcmp($post['password'], $post['password_confirm']) <> 0) {
$_SESSION['flash'] = [
'error' => 1,
'message' => 'Password does not match.'
];

header('Location: ' . $redirect_back_url);
exit;
}

if (!$stmt = mysqli_prepare($db_connection, 'SELECT id FROM users WHERE email = ?')) {
die(mysqli_error($db_connection));
}

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

mysqli_stmt_execute($stmt);

// If user with email already exists, redirect back with proper alert message
if ($result = mysqli_stmt_fetch($stmt)) {
$_SESSION['flash'] = [
'error' => 1,
'message' => 'User with email already exists.'
];

header('Location: ' . $redirect_back_url);
exit;
}

mysqli_stmt_close($stmt);

// Prepare parameterized query
if (!$stmt = mysqli_prepare($db_connection, 'INSERT INTO users (name, email, password, token) VALUES (?, ?, ?, ?)')) {
die(mysqli_error($db_connection));
}

// Bind parameters to prepared query
mysqli_stmt_bind_param($stmt, 'ssss', $name, $email, $password, $token);

// Execute prepared statement
if (mysqli_stmt_execute($stmt)) {
$verification_link = BASE_URL . '/verify-registration.php?token=' . $token;

$subject = 'Account Verification';

$message = 'Click the link to verify account:' . PHP_EOL;
$message .= '<a href="' . $verification_link . '">Verify Account</a>';

$headers = [
'Content-type' => 'text/html; charset=utf-8',
'From' => '[email protected]'
];

// Send email to user for verification
mail($post['email'], $subject, $message, $headers);

$_SESSION['flash'] = [
'message' => 'Registration successful! Please check your email to verify your account.'
];

// Redirect back with success message
header('Location: ' . $redirect_back_url);
exit;
}

mysqli_stmt_close($stmt);

// Close the connection
mysqli_close($db_connection);
}

// Fallback error message and redirect
$_SESSION['flash'] = [
'error' => 1,
'message' => 'Something went wrong! please try again.'
];

header('Location: ' . $redirect_back_url);
exit;
 

Step 5: Verify User Email (PHP Script)

We create a verify-registration.php script to verify the user's email address. When the user clicks the email verification link in the email, the user will be redirected to this script. This is what this script will do:

  • Start the session on this page as well if it has not already started.
  • Include the constants file and store the login page URL in the $login_url variable.
  • Sanitize the unique token in the URL using the filter_input() function of PHP.
  • If the token is empty or not set, stop further code execution with die and a proper message.
  • Establish a database connection and get the user from the database against the verification token.
  • If no record for the verification token is returned, stop execution of the code with a proper message.
  • Finally, set the token to NULL and is_verified to 1 in the database; this will be used in the user login script, where the user will be able to log in with provided credentials.
  • Redirect the user to the login page with an email verification successful message.
verify-registration.php 
<?php
if (!session_id()) {
session_start();
}

include_once 'constants.php';

// Change it to login form page
$login_url = filter_var(BASE_URL, FILTER_SANITIZE_URL);

$token = filter_input(INPUT_GET, 'token');

if (empty($token)) {
die('Token is missing!');
}

$db_connection = mysqli_connect(DB_HOST, DB_USER, DB_PASSWORD, DB_NAME) OR die(mysqli_connect_error());

// Prepare parameterized query to get user
if (!$stmt = mysqli_prepare($db_connection, 'SELECT id FROM users WHERE token = ?')) {
die(mysqli_error($db_connection));
}

// Bind params and execute statement
mysqli_stmt_bind_param($stmt, 's', $token);
mysqli_stmt_execute($stmt);

if (!mysqli_stmt_fetch($stmt)) {
die('Invalid token');
}

mysqli_stmt_close($stmt);

// Prepare parameterized query for update
if (!$stmt = mysqli_prepare($db_connection, 'UPDATE users SET is_verified = 1, token = NULL WHERE token = ?')) {
die(mysqli_error($db_connection));
}

// Bind params and execute statement
mysqli_stmt_bind_param($stmt, 's', $token);

mysqli_stmt_execute($stmt);
mysqli_stmt_close($stmt);

// Close the connection
mysqli_close($db_connection);

// Set session message and redirect to login page
$_SESSION['flash'] = [
'message' => 'Account has been successfully verified.'
];

header('Location: ' . $login_url);
exit;

We just demonstrated how to create a simple user registration form in PHP and send an email verification link to the user with a unique token. The code snippets can be modified as needed. By generating unique tokens and an email verification link, we make sure only real users get registered in the application.