Simple User Registration in PHP

User registration is a feature which allows users to create their own accounts to access certain area of an application. Learn in this post how to signup users in PHP in simple and easy steps.

Simple User Registration in PHP

Many web applications use user registration feature to allow users to access certain area of application which only registered user is allowed to access like, 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 User in PHP (Step-by-Step)

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

 

Step 1: Database Structure

We need a users database table with proper structure 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` int NOT NULL AUTO_INCREMENT PRIMARY KEY,
`name` varchar(150) NOT NULL,
`email` varchar(255) 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 database and creating a verification link to verify email address of 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 user can enter details for registration. The form will contain name, email, password, and password_confirm fields to match both passwords user entered. This form will be handled on 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 user in 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 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 $tokenvariables from user submitted values.
  • Generate a random token for email verification.
  • Check if both passwords user entered are same. Redirect back with error message if they are not same.
  • Check a user with same email already does not exist. If the email is already in use, redirect back with error message.
  • Save the user to database table with parameterized queries.
  • Prepare an HTML message to send for email verification with verification token.
  • Send the registration verification email to user's email address.
  • Finally, redirect back with 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 verify-registration.php script to verify user email address. When user email verification link in email is clicked, user will be redirect to this script. This is what this script will do:

  • Start the session on this page as well if it is not already started.
  • Include constants file and store the login page URL in $login_url variable.
  • Sanitize the unique token in URL using the filter_input() function of PHP.
  • If token is empty or not set die the script with message.
  • Establish a database connection and get user from database against the verification token.
  • If no record for verification token is returned, die the script with proper message.
  • Finally, set the token to NULL and is_verified to 1 in database, this will be used in user login script where user will be able to login with provided credentials.
  • Redirect user to login page with 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 email verification link to user with unique token. The code snippets can be modified as needed. By generating unique tokens and email verification link we make sure only real users get registered in application.