0% found this document useful (0 votes)
151 views

Secure Registration System With PHP and MySQL 07069564369

This document discusses creating a secure registration system with PHP and MySQL. It covers designing a registration form with HTML and CSS, setting up required tables in a MySQL database, validating form data submitted to a PHP file, and implementing account activation functionality.

Uploaded by

All In One
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
151 views

Secure Registration System With PHP and MySQL 07069564369

This document discusses creating a secure registration system with PHP and MySQL. It covers designing a registration form with HTML and CSS, setting up required tables in a MySQL database, validating form data submitted to a PHP file, and implementing account activation functionality.

Uploaded by

All In One
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 14

8/25/23, 1:28 AM Secure Registration System with PHP and MySQL

Packages Tutorials Examples References Tools

HTML CSS JavaScript PHP Python MySQL

Secure Registration System with PHP and MySQL


Updated on January 11, 2023 by David Adams

This tutorial is a follow up to our previous tutorial Secure Login System with PHP and MySQL. In this tutorial,
we'll be creating a secure registration form and implementing basic validation.

A registration form is what your website's visitors can use to register their details, which will subsequently be
stored in a MySQL database and be used for authentication purposes.

The Advanced package includes additional features and a download link to the source code. In addition, it
includes the complete tutorial source code.

Contents

1 Getting Started

1.1 Requirements

1.2 What You Will Learn in this Tutorial

1.3 File Structure & Setup

2 Creating the Registration Form Design

3 Creating the Database and setting-up Tables

4 Registering Users with PHP & MySQL

5 Validating Form Data

6 Implementing Account Activation

1. Getting Started
There are a few steps we need to take before we create our secure registration system. We need to set up
our web server environment and make sure we have the required extensions enabled (skip if you followed
the secure login system tutorial).

1.1. Requirements

If you haven't got a local web server set-up, you will need to download and install XAMPP. XAMPP is a
By using this website, you agree to our privacy policy and that we and our partners may set cookies for purposes such as customising
I understand
server-side
content web development environment that includes the essentials for back-end web developers.
and advertising.

https://codeshack.io/secure-registration-system-php-mysql/ 1/14
8/25/23, 1:28 AM Secure Registration System with PHP and MySQL

1.2. What You Will Learn in this Tutorial


Packages Tutorials Examples References Tools
Form Design — Design a registration form with HTML5 and CSS3.

Prepared SQL Queries — How to prepare SQL queries to prevent SQL injection and insert new records
into a MySQL database.

Basic Validation — Validating form data that is sent to the server (username, password, and email).

1.3. File Structure & Setup

We now need to start our web server and create the files and directories that we're going to use for our
registration system.

Open XAMPP Control Panel

Next to the Apache module click Start

Next to the MySQL module click Start

Navigate to XAMPPs installation folder (C:\xampp)

Open the htdocs folder

Create the following folders and files:

File Structure

\-- phplogin
    |-- register.html

    |-- style.css
    |-- register.php

    |-- activate.php (optional)

Each file will contain the following:

register.html — Registration form created with HTML5 and CSS3. As this file doesn't require us to use
PHP, we'll save it as plain HTML.

style.css — The stylesheet (CSS3) for our secure registration form.

register.php — Validate form data and insert a new account into the MySQL database.

activate.php — Activate the user's account with a unique code (email-based activation).

2. Creating the Registration Form Design


The registration form will be used by our website's visitors. They can use it to input their account information
seamlessly. We'll be creating the registration form with HTML and CSS.

Edit the register.html file and add the following code:

HTML  Copy

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Register</title>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.2.0/css/
</head>
<body>
<div class="register">
<h1>Register</h1>
<form action="register.php" method="post" autocomplete="off">
<label for="username">
<i class="fas fa-user"></i>
By using this website, you agree to our privacy policy and that we and our partners may set cookies for purposes such as customising
</label>
content and advertising.
<input type="text" name="username" placeholder="Username" id="username" required>

https://codeshack.io/secure-registration-system-php-mysql/ 2/14
8/25/23, 1:28 AM Secure Registration System with PHP and MySQL
<label for="password">
Packages
<i class="fas fa-lock"></i> Tutorials Examples References Tools
</label>
<input type="password" name="password" placeholder="Password" id="password" require
<label for="email">
<i class="fas fa-envelope"></i>
</label>
<input type="email" name="email" placeholder="Email" id="email" required>
<input type="submit" value="Register">
</form>
</div>
</body>
</html>

If we navigate to http://localhost/phplogin/register.html, our registration form will look like the following:

http://localhost/phplogin/register.html

Pretty basic for a registration form, right? Now let's spice it up a little and implement some CSS code. Edit
the style.css file, and add the following:

CSS  Copy

* {
box-sizing: border-box;
font-family: -apple-system, BlinkMacSystemFont, "segoe ui", roboto, oxygen, ubuntu, cantarell,
font-size: 16px;
}
body {
background-color: #435165;
margin: 0;
}
.register {
width: 400px;
background-color: #ffffff;
box-shadow: 0 0 9px 0 rgba(0, 0, 0, 0.3);
margin: 100px auto;
}
.register h1 {
text-align: center;
color: #5b6574;
font-size: 24px;
padding: 20px 0 20px 0;
border-bottom: 1px solid #dee0e4;
}
By using this
.register website,
form { you agree to our privacy policy and that we and our partners may set cookies for purposes such as customising
content and advertising.
display: flex;

https://codeshack.io/secure-registration-system-php-mysql/ 3/14
8/25/23, 1:28 AM Secure Registration System with PHP and MySQL
flex-wrap: wrap;
justify-content: center; Packages Tutorials Examples References Tools
padding-top: 20px;
}
.register form label {
display: flex;
justify-content: center;
align-items: center;
width: 50px;
height: 50px;
background-color: #3274d6;
color: #ffffff;
}
.register form input[type="password"], .register form input[type="text"], .register form input[type
width: 310px;
height: 50px;
border: 1px solid #dee0e4;
margin-bottom: 20px;
padding: 0 15px;
}
.register form input[type="submit"] {
width: 100%;
padding: 15px;
margin-top: 20px;
background-color: #3274d6;
border: 0;
cursor: pointer;
font-weight: bold;
color: #ffffff;
transition: background-color 0.2s;
}
.register form input[type="submit"]:hover {
background-color: #2868c7;
transition: background-color 0.2s;
}

We need to include our stylesheet in our register.html file, copy and paste the following code to the head
section:

HTML  Copy

<link href="style.css" rel="stylesheet" type="text/css">

And now our registration form will look more appealing:

http://localhost/phplogin/register.html

By using this website, you agree to our privacy policy and that we and our partners may set cookies for purposes such as customising
content and advertising.

https://codeshack.io/secure-registration-system-php-mysql/ 4/14
8/25/23, 1:28 AM Secure Registration System with PHP and MySQL

Let's narrow down the form so we can get a better understanding of what's going on.
Packages Tutorials Examples References Tools
Form — we need to use both the action and post attributes, the action attribute will be set to the
registration file. When the form is submitted, the form data will be sent to the registration file for
processing. The method attribute is set to post , which will enable us to process the form data using
the POST request method.
Input (text/password/email) — We need to name our form fields so the server can recognize
them, so if we set the value of the attribute name to the username , we can use the post variable
in our registration file to get the data, like this: $_POST['username'] .

Input (submit) — On click, the form data will be sent to our registration file for processing.

That's basically all we need to do on the client side. The next step is to set up the database and create the
registration file with PHP.

3. Creating the Database and setting-up Tables


You can skip this step if you followed the Secure Login System Tutorial.

For this part, you will need to access your MySQL database, either using phpMyAdmin or your preferred
MySQL database management application.

If you're using phpMyAdmin then follow these instructions:

Navigate to: http://localhost/phpmyadmin/

Click the Databases tab at the top

Under Create database, type in phplogin in the text box

Select utf8_general_ci as the collation

Click Create

You can use your own database name, but for this tutorial, we'll use phplogin.

What we need now is an accounts table that will store all our accounts (usernames, passwords, emails, etc.).

Click the database on the left side panel (phplogin) and execute the following SQL statement:

SQL  Copy

CREATE TABLE IF NOT EXISTS `accounts` (


`id` int(11) NOT NULL AUTO_INCREMENT,
`username` varchar(50) NOT NULL,
`password` varchar(255) NOT NULL,
`email` varchar(100) NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2 DEFAULT CHARSET=utf8;

On phpMyAdmin this should look like:

By using this website, you agree to our privacy policy and that we and our partners may set cookies for purposes such as customising
content and advertising.

https://codeshack.io/secure-registration-system-php-mysql/ 5/14
8/25/23, 1:28 AM Secure Registration System with PHP and MySQL

http://localhost/phpmyadmin/
Packages Tutorials Examples References Tools

The above SQL statement code will create the accounts table with the columns id , username , password ,
and email .

4. Registering Users with PHP & MySQL


Now we need to create the registration file that will process the form fields, check for basic validation, and
insert the new account into our database.

The registration page will require a connection to our database, and therefore we must include the necessary
variables and MySQL functions. Edit the register.php file and add the following code:

PHP  Copy

<?php
// Change this to your connection info.
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'phplogin';
// Try and connect using the info above.
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if (mysqli_connect_errno()) {
// If there is an error with the connection, stop the script and display the error.
exit('Failed to connect to MySQL: ' . mysqli_connect_error());
}

Don't forget to update the MySQL variables if your MySQL credentials do not reflect the declared values.

Next, we can add basic validation to ensure the user has entered their details and check for empty variables.

PHP  Copy

// Now we check if the data was submitted, isset() function will check if the data exists.
if (!isset($_POST['username'], $_POST['password'], $_POST['email'])) {
// Could not get the data that should have been sent.
exit('Please complete the registration form!');
}
// Make sure the submitted registration values are not empty.
if (empty($_POST['username']) || empty($_POST['password']) || empty($_POST['email'])) {
// One or more values are empty.
exit('Please complete the registration form');
} using this website, you agree to our privacy policy and that we and our partners may set cookies for purposes such as customising
By
content and advertising.

https://codeshack.io/secure-registration-system-php-mysql/ 6/14
8/25/23, 1:28 AM Secure Registration System with PHP and MySQL

Now, we need to check if the account already exists in the database. We can check this by selecting a record
Packages Tutorials Examples References Tools
from our accounts table with the same username that the user has provided.

Add after:

PHP  Copy

// We need to check if the account with that username exists.


if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP passwo
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->store_result();
// Store the result so we can check if the account exists in the database.
if ($stmt->num_rows > 0) {
// Username already exists
echo 'Username exists, please choose another!';
} else {
// Insert new account
}
$stmt->close();
} else {
// Something is wrong with the SQL statement, so you must check to make sure your accounts tabl
echo 'Could not prepare statement!';
}
$con->close();
?>

Replace:

// Insert new account

With:

PHP  Copy

// Username doesn't exists, insert new account


if ($stmt = $con->prepare('INSERT INTO accounts (username, password, email) VALUES (?, ?, ?)')) {
// We do not want to expose passwords in our database, so hash the password and use password_ve
$password = password_hash($_POST['password'], PASSWORD_DEFAULT);
$stmt->bind_param('sss', $_POST['username'], $password, $_POST['email']);
$stmt->execute();
echo 'You have successfully registered! You can now login!';
} else {
// Something is wrong with the SQL statement, so you must check to make sure your accounts tabl
echo 'Could not prepare statement!';
}

This will insert a new account into our accounts table.

Did You Know?


 Implementing prepared SQL statements will prevent SQL injection, but only if used correctly.

Remember in our Login System we implemented the password_verify function? As you can see in the code
above we're leveraging the password_hash function as it will encrypt the user's password using a one-way
algorithm — it will help prevent your users' passwords from being exposed if for somehow your database
becomes vulnerable.

That's basically all we need to do to register accounts on our website.

5. Validating Form Data


Byalready
We using this website,
have you agreeintoour
basic validation ourPHP
privacy policy
script, but and
whatthat wewant
if we and our partners
to check may
if the setis
email cookies foranpurposes such as customising
actually
content and advertising.
email or if the username and password should be a certain number of characters long? You can do that with

https://codeshack.io/secure-registration-system-php-mysql/ 7/14
8/25/23, 1:28 AM Secure Registration System with PHP and MySQL

the codes below. Add them to the register.php file before the following line:
Packages Tutorials Examples References Tools

if ($stmt = $con->prepare('SELECT id, password FROM accounts WHERE username = ?')) {

Email Validation

The below snippet will make sure the captured input value is an email address.

PHP  Copy

if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
exit('Email is not valid!');
}

Invalid Characters Validation

The below snippet will only accept alphabetical and numerical characters.

PHP  Copy

if (preg_match('/^[a-zA-Z0-9]+$/', $_POST['username']) == 0) {
exit('Username is not valid!');
}

Character Length Check

The below snippet will enforce the password field to be between 5 and 20 characters long.

PHP  Copy

if (strlen($_POST['password']) > 20 || strlen($_POST['password']) < 5) {


exit('Password must be between 5 and 20 characters long!');
}

You should always implement your own validation as these are just basic examples.

6. Implementing Account Activation


The account activation system will send an email to the user with the activation link when the user has
registered.

The first thing we need to do is to go into phpMyAdmin and select our database, in our case this would be
phplogin, you can either add the column activation_code to the accounts table or execute the SQL
statement below.

SQL  Copy

ALTER TABLE accounts ADD activation_code varchar(50) DEFAULT ''

Now we need to edit our register.php file, search for this line of code:

if ($stmt = $con->prepare('INSERT INTO accounts (username, password, email) VALUES (?, ?, ?)')) {

Replace with:

PHP  Copy

if ($stmt = $con->prepare('INSERT INTO accounts (username, password, email, activation_code) VALUES

Search for:
By using this website, you agree to our privacy policy and that we and our partners may set cookies for purposes such as customising
content and advertising.

https://codeshack.io/secure-registration-system-php-mysql/ 8/14
8/25/23, 1:28 AM Secure Registration System with PHP and MySQL

$stmt->bind_param('sss', $_POST['username'], $password, $_POST['email']);


Packages Tutorials Examples References Tools

Replace with:

PHP  Copy

$uniqid = uniqid();
$stmt->bind_param('ssss', $_POST['username'], $password, $_POST['email'], $uniqid);

The $uniqud variable will generate a unique ID that we'll use for our activation code, this will be sent to the
user's email address.

Search for:

echo 'You have successfully registered, you can now login!';

Replace with:

PHP  Copy

$from = '[email protected]';
$subject = 'Account Activation Required';
$headers = 'From: ' . $from . "\r\n" . 'Reply-To: ' . $from . "\r\n" . 'X-Mailer: PHP/' . phpversio
// Update the activation variable below
$activate_link = 'http://yourdomain.com/phplogin/activate.php?email=' . $_POST['email'] . '&code='
$message = '<p>Please click the following link to activate your account: <a href="' . $activate_lin
mail($_POST['email'], $subject, $message, $headers);
echo 'Please check your email to activate your account!';

Upon account registration, the user will need to activate their account using the activation link that is sent to
their email address. You need to update both the $from and $activate_link variables.

After, we can proceed to create the activation file. The activation file will process the GET parameters and
verify the email and code. The user's account will be activated if the code is valid.

Edit/create the activate.php file and add the following code:

PHP  Copy

<?php
// Change this to your connection info.
$DATABASE_HOST = 'localhost';
$DATABASE_USER = 'root';
$DATABASE_PASS = '';
$DATABASE_NAME = 'phplogin';
// Try and connect using the info above.
$con = mysqli_connect($DATABASE_HOST, $DATABASE_USER, $DATABASE_PASS, $DATABASE_NAME);
if (mysqli_connect_errno()) {
// If there is an error with the connection, stop the script and display the error.
exit('Failed to connect to MySQL: ' . mysqli_connect_error());
}
// First we check if the email and code exists...
if (isset($_GET['email'], $_GET['code'])) {
if ($stmt = $con->prepare('SELECT * FROM accounts WHERE email = ? AND activation_code = ?')) {
$stmt->bind_param('ss', $_GET['email'], $_GET['code']);
$stmt->execute();
// Store the result so we can check if the account exists in the database.
$stmt->store_result();
if ($stmt->num_rows > 0) {
// Account exists with the requested email and code.
if ($stmt = $con->prepare('UPDATE accounts SET activation_code = ? WHERE email = ? AND
// Set the new activation code to 'activated', this is how we can check if the user
$newcode = 'activated';
$stmt->bind_param('sss', $newcode, $_GET['email'], $_GET['code']);
$stmt->execute();
echo 'Your account is now activated! You can now <a href="index.html">login</a>!';
By using this website,
} you agree to our privacy policy and that we and our partners may set cookies for purposes such as customising
content and advertising.
} else {

https://codeshack.io/secure-registration-system-php-mysql/ 9/14
8/25/23, 1:28 AM Secure Registration System with PHP and MySQL
echo 'The account is already activated or doesn\'t exist!';
} Packages Tutorials Examples References Tools
}
}
?>

If the code reflects the one in the database that is associated with the user's account then the value of the
activation_code column will be updated to activated .

If we want to check if the user has activated their account, we can add the following code to the pages we
want to restrict non-activated users:

PHP  Copy

if ($account['activation_code'] == 'activated') {
// account is activated
// Display home page etc
} else {
// account is not activated
// redirect user or display an error
}

For the above code to work, you will need to connect to your MySQL database and select the user's account.

Also, take note PHP mail function will only work if your computer or server supports it. If it doesn't send an
email, check your configuration or install a mail server such as Postfix.

Conclusion
Congratulations! You've successfully created a Login System (if you followed the previous tutorial) and
registration system with PHP and MySQL. You're free to use the code in this tutorial and adapt it for use in
your own projects.

Remember that this is just a secure base that you should work from. Consider changing or implementing
your own validation, and implement your own features.

If you would like more of this tutorial series, feel free to drop a comment and suggest to us what we could
create next.

Enjoy coding!

If you would like to support us, consider purchasing the advanced secure login & registration system below
as it will greatly help us create more tutorials and keep our website up and running. The advanced package
includes improved code and more features.

Sale
ADVANCED BUNDLE (SAVE 59%)

$ 20.00 $ 119.00 290.00


view more details view more details

Source Code  Secure Login & Registration System 

Database SQL File  Shopping Cart System 

Secure Login & Registration System  CRUD Application 

Home, Profile & Edit Profile Pages  Ticketing System 

By using this website, you agree to our privacy policy and that we and our partners may set cookies for purposes such as customising
Account
content and Activation Feature 
advertising. Gallery System 

https://codeshack.io/secure-registration-system-php-mysql/ 10/14
8/25/23, 1:28 AM Secure Registration System with PHP and MySQL

Remember Me Feature  Event Calendar System 


Packages Tutorials Examples References Tools

AJAX Integration  Poll and Voting System 

PDO, MVC OOP & Basic Versions  Commenting System 

Admin Panel  Review System 

Add-on: Forgot Password  Contact Form 

Add-on: Brute Force Protection  Live Support Chat System 

Add-on: CSRF Protection  Newsletter & Mailing System 

Add-on: Two-factor Authentication  File Management System 

Add-on: Native Captcha  Access to future scripts 

Add-on: reCAPTCHA v3 

Add-on: Google OAuth 

Add-on: Facebook OAuth 

Responsive Design (mobile-friendly) 

SCSS File 

Commented Code 

Free Updates & Support (minor issues) 

User Guide 

Extra: Tutorial Source Code 

PayPal
PayPal
Download Download

Stripe
Stripe
Download Download

Crypto
Crypto
Download Download

   

ABOUT AUTHOR

By using this website, you agree to our privacy policy and that we and our partners may set cookies for purposes such as customising
content and advertising.

https://codeshack.io/secure-registration-system-php-mysql/ 11/14
8/25/23, 1:28 AM Secure Registration System with PHP and MySQL

David Adams
Packages Tutorials Examples References Tools
Enthusiastic website developer, I've been designing and developing web
applications for over 10 years, I enjoy the creativity I put into my projects
and enjoy what others bring to the awesome web. My goal is to help
newcomers learn the ways of the web.

form mysql mysqli php programming register registration tutorials

← Secure Login System with PHP and MySQL Pure CSS3 and HTML5 Tooltips →

RELATED POSTS

Shopping Cart System with PHP Live Support Chat with AJAX, PHP Poll and Voting System with PHP
and MySQL and MySQL and MySQL

782 Comments 
1 Login

G Join the discussion…

LOG IN WITH OR SIGN UP WITH DISQUS ?

Name

 11 Share Best Newest Oldest

Marcel Deen − ⚑
a month ago edited

Dear David,

Could you help me to configure PHPmailer with secure-registration-system? Many things work for me but I
can't get this to work. PHPmailer works by itself. I'd be happy to put something saa compensation in
return, just let me know. I have now placed standard PHPMailer code in top of register-process.php. But I
understand that this code may need to be modified so that register.php correctly sends its data here. For
the rest, the system works very well and we can also learn a lot from it, thanks again. This is the code as it

Design and Development


tips in your inbox. Every
weekday.

ADS VIA CARBON

Search blog ... 


Become a Subscriber
Stay up to date and join our newsletter to
By using thisreceive
website, you agree
the latest to our privacy policy and that we and our partners may set cookies for purposes such as customising
updates.
content and advertising.

https://codeshack.io/secure-registration-system-php-mysql/ 12/14
8/25/23, 1:28 AM Secure Registration System with PHP and MySQL

Email Address Packages Tutorials Examples References Tools

Subscribe

FOLLOW US

  

RECENT POSTS

Build an AI-Powered Chatbot with OpenAI,


ChatGPT, and JavaScript

RSS News Feed with PHP and MySQL

Elegant Toast Notifications with JavaScript

TAGS

tutorials php programming mysql

javascript css ajax freebies

snippets html form php class

login mysqli scripting pdo

registration shopping cart

javascript class register cookie

gallery system pagination mailing list

content locker live support chat sessions

hotel reservation form poll system

template flask ticketing system

columns toast notifications database

snippet progress bar newsletter system

js node.js express contact

commenting system mvc event calendar

table review system progamming

file upload survey form jquery

voting system crud python modals

sort

By using this website, you agree to our privacy policy and that we and our partners may set cookies for purposes such as customising
content and advertising.

https://codeshack.io/secure-registration-system-php-mysql/ 13/14
8/25/23, 1:28 AM Secure Registration System with PHP and MySQL

Packages Tutorials Examples References Tools

CODESHACK.IO FOLLOW US

Tools About Us
Packages
 
Live Code Editor Contact Us
Tutorials
JSON Sorter Privacy Policy
Examples
Resend a Receipt Terms
References

© 2023 CodeShack. All Rights Reserved. By using this website you accept the terms and conditions.

By using this website, you agree to our privacy policy and that we and our partners may set cookies for purposes such as customising
content and advertising.

https://codeshack.io/secure-registration-system-php-mysql/ 14/14

You might also like